Java线程(24):新特征-条件变量(四)

2014-11-24 08:24:20 · 作者: · 浏览: 2
g name; //操作人
private MyCount myCount; //账户
private int x; //存款金额
DrawThread(String name, MyCount myCount, int x) {
this.name = name;
this.myCount = myCount;
this.x = x;
}
public void run() {
myCount.drawing(x, name);
}
}
/**
* 普通银行账户,不可透支
*/
class MyCount {
private String oid; //账号
private int cash; //账户余额
MyCount(String oid, int cash) {
this.oid = oid;
this.cash = cash;
}
/**
* 存款
*
* @param x 操作金额
* @param name 操作人
*/
public void saving( int x, String name) {
if (x > 0) {
synchronized ( this) {
cash += x; //存款
System.out.println(name + "存款" + x + ",当前余额为" + cash);
notifyAll(); //唤醒所有等待线程。
}
}
}
/**
* 取款
*
* @param x 操作金额
* @param name 操作人
*/
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(); //唤醒所有存款操作
}
}
李四存款3600,当前余额为13600
王五取款2700,当前余额为10900
老张存款600,当前余额为11500
老牛取款1300,当前余额为10200
胖子取款800,当前余额为9400
张三存款2000,当前余额为11400
Process finished with exit code 0
对比以上三种方式,从控制角度上讲,第一种最灵活,第二种代码最简单,第三种容易犯错。