/*
//这个代码运行结果正确
class Bank {
Object obj = new Object();
private int sum;
public void add(int n) {
synchronized (obj) {
sum = sum + n;
try {
wait(10);
} catch (Exception e) {
}
System.out.println("sum = " + sum);
}
}
}*/
class Bank
{
private int sum;
public synchronized void add (int n)
{
sum = sum +n;
//这里的wait改成Thread.sleep(10); 代码运行没问题.问题,为什么用wait时,锁代码块没问题,锁方法就有问题
try{wait(10);}catch (Exception e){}
System.out.println("sum = "+sum);
}
}
class Cus implements Runnable {
Bank b = new Bank();
public void run() {
for (int x = 0; x < 3; x++) {
b.add(100);
}
}
}
class Demo {
public static void main(String[] args) {
Cus c = new Cus();
Thread t1 = new Thread(c);
Thread t2 = new Thread(c);
t1.start();
t2.start();
}
}