notify唤醒顺序疑问
来源:7-3 notify方法

风刚才唱歌
2021-11-15
老师下面代码循环调用notify哪里 Thread.sleep(100);注释掉阻塞顺序和唤醒顺序不一致,加上阻塞顺序和唤醒顺序一致。请问这是为什么
public class WaitNotifyWakeOrder implements Runnable{
private static Object lock = new Object();
private static List<String> waitList = new ArrayList<>();
private static List<String> notifyList = new ArrayList<>();
public static void main(String[] args) throws InterruptedException {
WaitNotifyWakeOrder wakeOrder = new WaitNotifyWakeOrder();
for (int i = 0; i < 10; i++) {
Thread thread = new Thread(wakeOrder);
thread.start();
}
Thread.sleep(100);
for (int i = 0; i < 10; i++) {
synchronized (lock){
lock.notify();
}
// Thread.sleep(100);
}
Thread.sleep(100);
System.out.println(waitList);
System.out.println(notifyList);
}
@Override
public void run() {
synchronized (lock){
System.out.println(Thread.currentThread().getName() + "准备阻塞");
try {
waitList.add(Thread.currentThread().getName());
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
notifyList.add(Thread.currentThread().getName());
System.out.println(Thread.currentThread().getName() + "被唤醒,执行完成");
}
}
}
写回答
1回答
-
悟空
2021-11-16
加了sleep也无法保证顺序,我的执行结果:
Thread-0准备阻塞
Thread-3准备阻塞
Thread-2准备阻塞
Thread-1准备阻塞
Thread-5准备阻塞
Thread-4准备阻塞
Thread-6准备阻塞
Thread-7准备阻塞
Thread-8准备阻塞
Thread-9准备阻塞
Thread-0被唤醒,执行完成
Thread-3被唤醒,执行完成
Thread-2被唤醒,执行完成
Thread-1被唤醒,执行完成
Thread-5被唤醒,执行完成
Thread-4被唤醒,执行完成
Thread-6被唤醒,执行完成
Thread-7被唤醒,执行完成
Thread-8被唤醒,执行完成
Thread-9被唤醒,执行完成
[Thread-0, Thread-3, Thread-2, Thread-1, Thread-5, Thread-4, Thread-6, Thread-7, Thread-8, Thread-9]
[Thread-0, Thread-3, Thread-2, Thread-1, Thread-5, Thread-4, Thread-6, Thread-7, Thread-8, Thread-9]
Process finished with exit code 0
042021-11-17
相似问题