放开A代码会发现所有线程都能到达partA。==> wait是会释放锁的
交替放开B和C ,依次随机一个到达partB或者所有到达partB==> notify 通知任意wait,notifyAll 通知所有
package org.he.util;
/**
* @author BenSon He
* @email qing878@gmail.com ,qq 277803242
* @since 20/11/2012
*/
public class Test extends Thread {
Object lock = null;
boolean notifyFlag = false;
public Test(Object lock, boolean notifyFlag) {
this.lock = lock;
this.notifyFlag = notifyFlag;
}
@Override
public void run() {
synchronized (lock) {
System.out.println((notifyFlag == true ? "(notifyThread)" : "") + Thread.currentThread().getName()
+ " hava in partA");
try {
// Thread.sleep(10000); // A
if (notifyFlag)
lock.notifyAll(); // C
// lock.notify(); // B
else
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println((notifyFlag == true ? "(notifyThread)" : "") + Thread.currentThread().getName()
+ " hava in partB");
}
}
public static void main(String[] args) throws InterruptedException {
Object lock = new Object();
new Test(lock, false).start();
new Test(lock, false).start();
new Test(lock, false).start();
Thread.sleep(10000);
new Test(lock, true).start();
}
}
