public void saving(int x, String name) {
if (x > 0) {
synchronized (this) {
cash += x; //存款 System.out.println(name + "存款" + x + ",当前余额为" + cash);
notifyAll(); //唤醒所有等待线程。
}
}
} public synchronized void drawing(int x, String name) {
synchronized (this) {
if (cash - x < 0) {
try { wait();
} catch (InterruptedException e1) {
e1.printStackTrace();
}
} else {
cash -= x; //取款 System.out.println(name + "取款" + x + ",当前余额为" + cash);
}
} notifyAll(); //唤醒所有存款操作
}
Java线程:新特征-条件变量(7)
最新推荐文章于 2025-12-24 10:29:31 发布
本文提供了一个使用Java实现的银行账户存款和取款操作的示例,通过`synchronized`关键字确保了线程间的同步,并利用`wait()`和`notifyAll()`来协调线程之间的等待与唤醒状态。
5069

被折叠的 条评论
为什么被折叠?



