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


0
4
悟空
回复
风刚才唱歌
这个我也不清楚,不好意思同学,因为JDK注释写的是唤醒是任意的,并且可以根据实现情况进行选择。
2021-11-17
共4条回复

线程八大核心+Java并发原理及企业级并发解决方案

完整的并发知识网络+丰富的工作内容分享+50余道并发高频面试题

2512 学习 · 939 问题

查看课程