[英]My synchronization doesn't work
我试图用synchronized
和ReentrantLock
在Bank.transfer,但我得到的输出是这样的:
“从7到3转移了82.0。总计918”,“从0到4转移了27.0。总计973”
虽然Total必须等于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;
}
}
在完成交易双方之后,计算总金额...即,将Account。[to] + =金额后的System.println移动。
这部分看起来很奇怪:
accounts[from] -= amount;
System.out.println("From " + from + " to " + to + " transfered " + amount + ". Total " + getTotal());
accounts[to] += amount;
您要在转移完成之前打印总数。
您要从一个帐户中扣除这笔钱之后, 再将其添加到另一个帐户中之前 ,调用getTotal()
。 始终显示少于100的金额。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.