码迷,mamicode.com
首页 > 其他好文 > 详细

使用Semaphore同步,经典银行账户问题

时间:2019-04-26 00:26:06      阅读:162      评论:0      收藏:0      [点我收藏+]

标签:final   port   zha   nts   java7   exception   color   except   信号   

1.新建Account类,使用Semaphore同步增加和减少金额方法。

package com.xkzhangsan.semaphorepack.bank;

import java.util.concurrent.Semaphore;

public class Account {
    
    private double balance;
    
    private final Semaphore semaphore = new Semaphore(1);
    
    public void addAmount(double amount){
        try {
            semaphore.acquire();
            double tmp = balance;
            Thread.sleep(10);
            tmp+=amount;
            balance=tmp;
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            semaphore.release();
        }
    }

    public void substractAmount(double amount){
        try {
            semaphore.acquire();
            double tmp = balance;
            Thread.sleep(10);
            tmp-=amount;
            balance=tmp;
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            semaphore.release();
        }
    }
    

    public double getBalance() {
        return balance;
    }

    public void setBalance(double balance) {
        this.balance = balance;
    }
    
    

}

2.其他和https://www.cnblogs.com/xkzhangsanx/p/10759690.html一致。

注意释放信号量

        } finally {
            semaphore.release();
        }

3.测试结果

Account start money:1000.000000
Company add 1000 balance:2000.0
Bank substract 1000 balance:1000.0
Company add 1000 balance:2000.0
Bank substract 1000 balance:1000.0
Company add 1000 balance:2000.0
Bank substract 1000 balance:1000.0
Company add 1000 balance:2000.0
Bank substract 1000 balance:1000.0
Company add 1000 balance:2000.0
Bank substract 1000 balance:1000.0
Company add 1000 balance:2000.0
Bank substract 1000 balance:1000.0
Company add 1000 balance:2000.0
Bank substract 1000 balance:1000.0
Company add 1000 balance:2000.0
Bank substract 1000 balance:1000.0
Company add 1000 balance:2000.0
Bank substract 1000 balance:1000.0
Company add 1000 balance:2000.0
Bank substract 1000 balance:1000.0
Account end money:1000.000000

参考:java7并发编程实战手册

GitHub地址:https://github.com/xkzhangsan/java-concurrent-practice

使用Semaphore同步,经典银行账户问题

标签:final   port   zha   nts   java7   exception   color   except   信号   

原文地址:https://www.cnblogs.com/xkzhangsanx/p/10771760.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!