线程同步问题
package zxd.work622;
public class TestAccount extends Thread {
private Account a = new Account();
public void run() {
for (int i = 0; i < 10; i++) {
this.makeWithDraw(100);
if (a.getBlance() < 0) {
System.out.println("余额透支");
}
}
}
private synchronized void makeWithDraw(int money) {//线程同步
synchronized (a) { //线程同步
if (money <= a.getBlance()) {
System.out.println("准备取款");
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
a.withDraw(money);
System.out.println(Thread.currentThread().getName() + "取了"
+ money + "余额:" + a.getBlance());
} else {
System.out.println("余额不足:" + Thread.currentThread().getName()
+ "取款失败");
}
}
}
public static void main(String[] args) {
TestAccount t = new TestAccount();
Thread one = new Thread(t);
Thread two = new Thread(t);
one.setName("张三");
two.setName("李四");
one.start();
two.start();
}
}