请稍等 ...
×

采纳答案成功!

向帮助你的同学说点啥吧!感谢那些助人为乐的人

notify唤醒顺序疑问

老师下面代码循环调用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() + "被唤醒,执行完成");
        }
    }
}

正在回答 回答被采纳积分+3

1回答

悟空 2021-11-16 14:07:29

加了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 回复 有任何疑惑可以回复我~
  • 提问者 风刚才唱歌 #1
    就是有sleep才一致的
    waitList: [Thread-0, Thread-3, Thread-4, Thread-2, Thread-1, Thread-5, Thread-6, Thread-7, Thread-8, Thread-9]
    notifyList: [Thread-0, Thread-3, Thread-4, Thread-2, Thread-1, Thread-5, Thread-6, Thread-7, Thread-8, Thread-9]
    没有的话是不一致的
    waitList: [Thread-0, Thread-2, Thread-1, Thread-3, Thread-4, Thread-5, Thread-6, Thread-7, Thread-8, Thread-9]
    notifyList: [Thread-0, Thread-9, Thread-8, Thread-7, Thread-6, Thread-5, Thread-4, Thread-3, Thread-1, Thread-2]
    回复 有任何疑惑可以回复我~ 2021-11-16 21:22:33
  • 悟空 回复 提问者 风刚才唱歌 #2
    notify方法注释说:如果有任何线程在此对象上等待,则选择其中一个唤醒。该选择是任意的,并且可以根据实现情况进行选择。
    回复 有任何疑惑可以回复我~ 2021-11-16 23:16:12
  • 提问者 风刚才唱歌 回复 悟空 #3
    老师我是想问  加上sleep和不加sleep为什么会有不一样的效果?
    回复 有任何疑惑可以回复我~ 2021-11-17 19:12:41
问题已解决,确定采纳
还有疑问,暂不采纳
意见反馈 帮助中心 APP下载
官方微信