作者热门文章
- iOS/Objective-C 元类和类别
- objective-c - -1001 错误,当 NSURLSession 通过 httpproxy 和/etc/hosts
- java - 使用网络类获取 url 地址
- ios - 推送通知中不播放声音
<分区>
我的导师说要使用多线程来更新帐户管理系统。下面给出了该系统的粗略概念。
这是我的源代码。
账户类别
public class Account {
int balance= 1000;
public int getBal(){
return balance;
}
public void withdraw(int bal){
balance= balance-bal;
}
public void deposit(int bal){
balance= balance+bal;
}
}
ThreadExercise 类
public class ThreadExercise implements Runnable{
Account acc = new Account();
public static void main(String[] args) {
ThreadExercise ts = new ThreadExercise();
Thread t1 = new Thread(ts, "person 1");
Thread t2 = new Thread(ts, "person 2");
Thread t3 = new Thread(ts, "person 3");
t1.start();
t2.start();
t3.start();
}
@Override
public void run() {
for (int i = 0; i < 3; i++) {
makeWithdraw(100);
if (acc.getBal() < 0) {
System.out.println("account is overdrawn!");
}
deposit(200);
}
}
private synchronized void makeWithdraw(int bal){
if (acc.getBal()>=bal) {
System.out.println(Thread.currentThread().getName()+" "+ "is try to withdraw");
try {
Thread.sleep(100);
} catch (Exception e) {
e.printStackTrace();
}
acc.withdraw(bal);
System.out.println(Thread.currentThread().getName()+" "+ "is complete the withdraw");
}else{
System.out.println(Thread.currentThread().getName()+ " "+"doesn't have enough money for withdraw ");
}
}
private synchronized void deposit(int bal){
if (bal>0) {
System.out.println(Thread.currentThread().getName()+" "+ " is try to deposit");
try {
Thread.sleep(100);
} catch (Exception e) {
e.printStackTrace();
}
acc.deposit(bal);
System.out.println(Thread.currentThread().getName()+" "+ "is complete the deposit");
}else{
System.out.println(Thread.currentThread().getName()+ " "+"doesn't have enough money for deposit");
}
}
}
代码运行良好。但我真的认为有些东西缺少这段代码。你能帮我找出那个错误吗?
同步 ThreadExercise 类中的 makeWithdraw() 和 deposit() 方法是否不够,我是否应该删除同步并同步 Account 类中的 withdraw() 和 deposit()。请给我一个清晰的思路。
感谢您的支持。
王者人生分享抽10Q币、现金、游戏钻石等 非必中 王者人生分享活动页面给随便一人 即可参与抽奖 奖品有10Q币、现金、游戏钻石等 亲测中10Q币 中了按照步骤兑换即可 活动地址:http:
微博新年许愿DNF抽5Q币+现金 亲测10Q币秒到 速度上 打开微博APP扫码进入活动界面 右上角如果没有红包 就关注并分享 然后在从自己的微博文章入口进入 进入以后再次点击红包 拆红包 红包需
我有个问题困扰了我一段时间。我尝试了一些解决方案,但没有奏效。 我有一个用于现金输入的文本框(例如 $999,99)。但是我需要自动输入“,”和“。”正确显示值。 我尝试了两种解决方案。其中之一是:
#include #include #include int main(void) { // prompt user for "0.00" value float dollars
我是一名优秀的程序员,十分优秀!