假如我们不用锁和条件变量,如何实现此功能呢?下面是实现代码: public synchronized void saving(int x, String name) {
if (x > 0) {
cash += x; //存款
System.out.println(name + "存款" + x + ",当前余额为" + cash);
}
notifyAll(); //唤醒所有等待线程。
}
public synchronized void drawing(int x, String name) {
if (cash - x < 0) {
try {
wait();
} catch (InterruptedException e1) {
e1.printStackTrace();
}
} else {
cash -= x; //取款
System.out.println(name + "取款" + x + ",当前余额为" + cash);
}
notifyAll(); //唤醒所有存款操作
}

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



