java - 我的同步不起作用

标签 java synchronization

我尝试在 Bank.transfer 中使用 synchronizedReentrantLock,但我得到如下输出:

"From 7 to 3 transfered 82.0. Total 918", "From 0 to 4 transfered 27.0. Total 973"

虽然总计必须等于 1000。请告诉我我错了什么?

public class expr {
    public static Bank b = new Bank();
    public static void main(String[] args) throws IOException, InterruptedException {
        for (int i = 0; i < 4; i++) {
            new BankTransfer();
        }
    }
}

public class BankTransfer implements Runnable{

    public BankTransfer() {
        Thread t = new Thread(this);
        t.start();
    }

    @Override
    public void run() {

        while (true){
            int from = (int) (expr.b.size * Math.random());
            int to = (int) (expr.b.size * Math.random());
            int amount = (int) (100 * Math.random());
            expr.b.transfer(from, to, amount);

            try {
                Thread.sleep((long) (2000 * Math.random()));
            } catch (InterruptedException e) {
                System.out.println("Thread was interrupted!");
                return;
            }

        }
    }


}

public class Bank {
    private int[] accounts;
    public int size = 10;
    private Lock block = new ReentrantLock();
    public boolean transfer(int from, int to, double amount){
        block.lock();
        try{
            if(accounts[from] >= amount && from != to){
                accounts[from] -= amount;
                System.out.println("From " + from + " to " + to + " transfered " + amount + ". Total " + getTotal());
                accounts[to] += amount;
                return true;
            }
        }finally {
            block.unlock();
        }
        return false;
    }
    public Bank(){
        accounts = new int[size];
        for (int i = 0; i < size; ++i) {
            accounts[i] = 100;
        }
    }
    private int getTotal(){
        int sum = 0;
        for (int i = 0; i < size; ++i) sum += accounts[i];
        return sum;
    }
}

最佳答案

在完成传输的两端后计算总数...即将 System.println 移到accounts[to] += amount 之后。

关于java - 我的同步不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9152666/

相关文章:

java - 使用 Apache POI 替换相关单元格后评估公式

java - kafka(不活动)消费者滞后监控

java - 关于同步方法、锁和监视器的说明

java - 尽管保护写操作仍获取竞争条件 - Java

java - 对于大量数据,是否有替代 AtomicReferenceArray 的方法?

java - boolean 输出阻塞整个过程

java - SMACK XEP-313 实现

java - Swing:区分用户引起的组件大小调整和自动组件大小调整的问题(编写自定义布局管理器)

java - 如果目标类方法同步,spring 代理调用是否也同步?

c++ - 为什么定时锁在C++0x中不会抛出超时异常?