我的同步不起作用

时间:2012-02-05 20:21:40

标签: java synchronization

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

  

“从7到3转移82.0。总计918”,“从0到4转移27.0。总计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;
    }
}

3 个答案:

答案 0 :(得分:3)

计算完成转换器两端后的总数...即在帐户[到] + =金额后移动System.println。

答案 1 :(得分:1)

这部分看起来很奇怪:

accounts[from] -= amount;
System.out.println("From " + from + " to " + to + " transfered " + amount + ". Total " + getTotal());
accounts[to] += amount;

您在传输完成之前打印总计

答案 2 :(得分:1)

您在从一个帐户扣除资金后拨打getTotal(),但之前将其添加到另一个帐户。它将始终显示少于100,转移的金额。