notify和notifyall有什么区别一直不是很清楚,做了如下测试:
public class SignalAllTest {
public static void main(String[] args) {
Object lock = new Object();
new Thread(()->{
try {
synchronized (lock){
lock.wait();
}
log.info("i am 1");
} catch (InterruptedException e) {
e.printStackTrace();
}
}).start();
new Thread(()->{
try {
synchronized (lock){
lock.wait();
}
log.info("i am 2");
} catch (InterruptedException e) {
e.printStackTrace();
}
}).start();
new Thread(()->{
synchronized (lock){
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
lock.notify();
}
}).start();
}
}
a、b两个线程都在wait,lock.notify的时候,只会有一个线程接触await状态,另外一个会一直等待下去。
而notifyAll会让两个线程都恢复执行,只是先后顺序并不确实。