//NotifyWaitTest.lock.notifyAll(); //# point 1 有异常发生
*2,notifyAll会唤醒该锁对象上所有等待的线程.
*3,TestThread1中的run方法中wait之后的代码是synchronized,唤醒的两个线程是一个执行完成之后,另外一个才能执行.
*4,如果在main方法中改用下面的方式notify,在"sent notification over"之后两个子线程才会从
wait暂停的地方继续执行,因为notify并不释放锁,这时候main还占用NotifyWaitTest.lock锁对象的锁.
[java]
System.out.println(Thread.currentThread().getName() + " sent notification 1");
NotifyWaitTest.lock.notify();
System.out.println(Thread.currentThread().getName() + " sent notification 2");
Thread.sleep(3000);
NotifyWaitTest.lock.notify();
System.out.println(Thread.currentThread().getName() + " sent notification over");
运行的结果为
Thread-0 wait for notification
Thread-1 wait for notification
main sent notification 1
main sent notification 2
main sent notification over
Thread-0 wake up
Thread-0 doing 0
Thread-0 doing 1
Thread-0 doing 2
Thread-0 finished
Thread-1 wake up
Thread-1 doing 0
Thread-1 doing 1
Thread-1 doing 2
Thread-1 finished
System.out.println(Thread.currentThread().getName() + " sent notification 1");
NotifyWaitTest.lock.notify();
System.out.println(Thread.currentThread().getName() + " sent notification 2");
Thread.sleep(3000);
NotifyWaitTest.lock.notify();
System.out.println(Thread.currentThread().getName() + " sent notification over");
Thread-0 wait for notification
Thread-1 wait for notification
main sent notification 1
main sent notification 2
main sent notification over
Thread-0 wake up
Thread-0 doing 0
Thread-0 doing 1
Thread-0 doing 2
Thread-0 finished
Thread-1 wake up
Thread-1 doing 0
Thread-1 doing 1
Thread-1 doing 2
Thread-1 finished如果在main方法中启动的是TestThread2,因为在TestThread2的run方法中wait之后的
代码不是synchronized的,所以wakeup之后可以并行执行.
[java] www.2cto.com
new TestThread2().start();
new TestThread2().start();
运行的结果是:
Thread-0 wait for notification
Thread-1 wait for notification
main sent notification all
Thread-0 wake up
Thread-1 wake up
Thread-0 doing 0
Thread-1 doing 0
Thread-0 doing 1
Thread-1 doing 1
Thread-0 doing 2
Thread-1 doing 2
作者:kkdelta