前面示例通过多次调用notify()
方法实现
5个线程被唤醒,但并不能保证系统中仅有
5个线程,也就是notify()方法的调用次数小于线程对象的数量,那么会出现部分线程对象没有被唤醒的情况。为了唤醒全部线程可以使用notifyAll()
方法。
注意
notifyAll()方法会按照执行
wait()方法的倒序依次对其他线程进行唤醒。
类MyService.java代码
package chapter3.test3_1.test3_1_14;
private Object lock = new Object();
public void waitMethod() {
System.out.println("begin wait " + System.currentTimeMillis() + " " + Thread.currentThread().getName());
System.out.println(" end wait " + System.currentTimeMillis() + " " + Thread.currentThread().getName());
} catch (InterruptedException e) {
public void notifyMethod() {
System.out.println("begin notify " + System.currentTimeMillis() + " " + Thread.currentThread().getName());
System.out.println(" end notify " + System.currentTimeMillis() + " " + Thread.currentThread().getName());
执行wait()方法的线程MyThreadA.java源代码
package chapter3.test3_1.test3_1_13;
public class MyThreadA extends Thread {
private MyService service;
public MyThreadA(MyService service) {
创建唤醒线程MyThreadB.java
package chapter3.test3_1.test3_1_13;
public class MyThreadB extends Thread {
private MyService service;
public MyThreadB(MyService service) {
Test.java代码
package chapter3.test3_1.test3_1_14;
public static void main(String[] args) throws InterruptedException {
MyService service = new MyService();
for (int i = 0; i < 10; i++) {
MyThreadA t1 = new MyThreadA(service);
MyThreadB t1 = new MyThreadB(service);
程序运行结果

唤醒的顺序是正序、倒序、随机,取决于具体的JVM实现,不是所有的JVM
在执行
notify()
时都是按调用wait()方法的正序进行唤醒的,也不是所有的
JVM在执行notifyAll()
时都是按调用
wait()方法的倒序进行唤醒的,具 体的唤醒顺序依赖于
JVM
的具体实现。