Java 并发编程:线程间的协作(wait/notify/sleep/yield/join)
对于notify/notifyAll方法的示例,会出现这种结果,很奇怪
也就是说notify()通知发出去了,没有线程开始执行。
public class JavaTest {
public synchronized void testWait() {
System.out.println(Thread.currentThread().getName() + " Start-----");
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + " End-------");
}
public static void main(String[] args) throws InterruptedException {
final JavaTest test = new JavaTest();
for (int i = 0; i < 5; i++) {
new Thread(new Runnable() {
@Override
public void run() {
test.testWait();
}
}).start();
}
synchronized (test) {
test.notify();
}
Thread.sleep(3000);
System.out.println("-----------分割线-------------");
synchronized (test) {
test.notifyAll();
}
}
}