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

Posted xkzhangsanx

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了使用Semaphore同步,经典银行账户问题相关的知识,希望对你有一定的参考价值。

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同步,经典银行账户问题的主要内容,如果未能解决你的问题,请参考以下文章

经典线程同步 信号量Semaphore

秒杀多线程第八篇 经典线程同步 信号量Semaphore

秒杀多线程第八篇 经典线程同步 信号量Semaphore

使用AtomicLong,经典银行账户问题

100个线程同时向一个银行账户中存入1元钱

同步监视器之同步代码块同步方法