notify
1、通知一个处于wait状态的线程进入block状态,此线程必须是和该对象相关联(同步)
notifyAll
1、通知所有处于wait状态的线程进入block状态,此线程必须是和该对象相关联(同步)
测试用例:
package p1;
public class A {
public static void main(String[] args) {
A1 a1 = new A1();
Runnable1 runnable1 = new Runnable1(a1);
Thread thread1 = new Thread(runnable1);
Thread thread2 = new Thread(runnable1);
Thread thread3 = new Thread(runnable1);
runnable1.thread1 = thread1;
runnable1.thread2 = thread2;
runnable1.thread3 = thread3;
thread1.start();
thread2.start();
thread3.start();
}
}
class A1 {
public void test(Thread thread1, Thread thread2, Thread thread3) {
synchronized (this) {
System.out.println("Thread id: " + Thread.currentThread().getId());
try {
for (int i = 0; i < 5; i++) {
System.out.println("+++++ " + i);
Thread.sleep(500);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
if (thread2.getId() == Thread.currentThread().getId()) { // 注意可能是thread2也可能是thread3
System.out.println("Thread 1 state: " + thread1.getState()); // Thread 1 state: WAITING
System.out.println("Thread 2 state: " + thread2.getState()); // Thread 2 state: RUNNABLE
System.out.println("Thread 3 state: " + thread3.getState()); // Thread 3 state: WAITING
notifyAll();
System.out.println("Thread 1 state: " + thread1.getState()); // Thread 1 state: BLOCKED
System.out.println("Thread 2 state: " + thread2.getState()); // Thread 2 state: RUNNABLE
System.out.println("Thread 3 state: " + thread3.getState()); // Thread 3 state: BLOCKED
// 注意: 上下两处代码分开运行,注释掉其中一部分
System.out.println("Thread 1 state: " + thread1.getState()); // Thread 1 state: WAITING
System.out.println("Thread 2 state: " + thread2.getState()); // Thread 2 state: RUNNABLE
System.out.println("Thread 3 state: " + thread3.getState()); // Thread 3 state: WAITING
notify();
System.out.println("Thread 1 state: " + thread1.getState()); // Thread 1 state: BLOCKED
System.out.println("Thread 2 state: " + thread2.getState()); // Thread 2 state: RUNNABLE
System.out.println("Thread 3 state: " + thread3.getState()); // Thread 3 state: WAITING
}
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Thread id: " + Thread.currentThread().getId());
try {
for (int i = 0; i < 5; i++) {
System.out.println("----- " + i);
Thread.sleep(500);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
class Runnable1 implements Runnable {
Thread thread1;
Thread thread2;
Thread thread3;
A1 a1;
public Runnable1(A1 a1) {
this.a1 = a1;
}
@Override
public void run() {
a1.test(thread1, thread2, thread3);
}
}