银行转账JAVA异常_Java多线程银行转账,同步问题

我正在尝试多线程银行转账问题。但是,我遇到了正确同步线程的问题。定期在线程执行账户之间的转账后,它将进行测试以确保没有钱获得或完全损失。Java多线程银行转账,同步问题

当一个线程进入测试方法时,它应该设置一个标志,以防止任何其他线程进入传输方法,然后等待所有当前正在执行的线程传输结束。

public void transfer(int from, int to, int amount) {

//finish running all threads' current transactions before test

accounts[from].waitForAvailableFunds(amount);

if (!open) return;

//checks to see if any thread is currently testing

//if so, wait

while(flag) {

try {

wait();

} catch (InterruptedException e) { /*ignore*/ }

}

//do not execute these two statements when a thread

//is performing a test

if (accounts[from].withdraw(amount)) {

accounts[to].deposit(amount);

}

if (shouldTest() && !flag) test();

}

//only one thread can perform a test at any given moment

public synchronized void test() {

//when test starts set a flag telling threads to

//not begin any new transfers

flag = true;

//wait for all threads currently performing transfers

//to finish current transfer before continuing

int sum = 0;

for (int i = 0; i < accounts.length; i++) {

System.out.printf("%s %s%n",

Thread.currentThread().toString(),accounts[i].toString());

sum += accounts[i].getBalance();

}

System.out.println(Thread.currentThread().toString() +

" Sum: " + sum);

if (sum != numAccounts * initialBalance) {

System.out.println(Thread.currentThread().toString() +

" Money was gained or lost");

System.exit(1);

} else {

System.out.println(Thread.currentThread().toString() +

" The bank is in balance");

}

//reset flag and notify threads test is complete.

flag = false;

notifyAll();

}

首先,我甚至不积极我已经设置了标志并正确等待。其次,如何让进入测试方法的线程等待所有其他正在执行传输的线程完成当前传输。

感谢

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值