- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在尝试多线程银行转账问题。但是,我在正确同步线程时遇到问题。线程在帐户之间执行转账后会定期进行测试,以确保没有获得或损失金钱。
当线程进入测试方法时,它应该设置一个标志来阻止任何其他线程进入传输方法,然后等待,直到当前执行传输的所有线程结束。
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();
}
首先,我什至不确定我是否已正确设置标志并等待。其次,如何让进入测试方法的线程等待所有其他已经在执行传输的线程来完成当前的传输。
谢谢
最佳答案
我认为你应该使用 volatile 来装饰该标志,以确保它在不同线程中更改时受到影响。
关于Java多线程银行转账、同步问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12682113/
stripe支付网关可以吗? 我们将使用 stripe 进行支付,首先我正在创建 token 。 $result = Stripe_Token::create(
最近一直在做一个有关信用卡系统的项目,所有很少出来给大家打招呼了,今天也该告一段了,本项目是基于python编程语言做的,此信用卡支持购物,转账和存取钱,下面小编把需求及实现思路大概分享一下,仅供参
1、要求 2、思路 1.购物类buy 接收 信用卡类 的信用卡可用可用余额, 返回消费金额 2.信用卡(ATM)类 接收上次操作后,信用卡可用余额,总欠款,剩余欠款,存款 其中:
您好,我正在将 MassPay Api 集成到我的项目中,我想通过集成在 codeigniter 上的 masspay api 发送批量付款。我为此创建了两个函数并获取相关 ID 和成功消息,但是当我
我是 MongoDB 新手我在银行做了一个简单的申请账户。一个账户可以给别人转账我这样设计帐户收集 account { name:A age: 24
我已经设置了一个支付门户,允许承包商将他们的账户信用余额转换为金钱(Cashout)并转入他们在 Paypal 上的账户。我的想法是将买家的电子邮件动态设置为承包商的 Paypal 电子邮件并运行快速
我是一名优秀的程序员,十分优秀!