优化代码运用线程知识package D18; public class D18_1 { public static void main(String[] args) { // TODO Auto-generated method stub } } class Account implements Runnable{ private int money; //修改方法 //存钱 public void deposit(int amount) { money +=amount; System.out.println("存钱成功,现有"+money); } @Override public void run() { // TODO Auto-generated method stub deposit(100); } public int getMoney() { return money; } public void setMoney(int money) { this.money = money; } }
时间: 2024-03-26 10:42:18 浏览: 56
以下是对代码的优化,使用线程来实现存钱和查询余额的功能:
```
public class D18_1 {
public static void main(String[] args) throws InterruptedException {
Account account = new Account();
Thread depositThread = new Thread(() -> {
for (int i = 0; i < 10; i++) {
account.deposit(100);
}
});
Thread checkThread = new Thread(() -> {
for (int i = 0; i < 10; i++) {
System.out.println("当前余额为:" + account.getMoney());
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
depositThread.start();
checkThread.start();
depositThread.join();
checkThread.join();
}
}
class Account {
private int money;
public synchronized void deposit(int amount) {
money += amount;
System.out.println("存钱成功,现有" + money);
}
public synchronized int getMoney() {
return money;
}
}
```
这里使用了 synchronized 关键字来保证线程安全,同时使用了 join() 方法来保证查询余额的线程在存钱线程执行完毕后才开始运行,避免了查询余额时余额数值不正确的问题。
阅读全文