notify() vs notifyAll()

notify() vs notifyAll()

import lombok.SneakyThrows;

import java.util.concurrent.TimeUnit;

public class T {
    @SneakyThrows
    public static void main(String[] args) {
        Object o = new Object();
        Thread thread1 = new Thread(() -> {
            try {
                synchronized (o) {
                    System.out.println(Thread.currentThread().getName() + "进入等待状态");
                    o.wait();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

        }, "线程1");


        Thread thread2 = new Thread(() -> {
            synchronized (o) {
                try {
                    System.out.println(Thread.currentThread().getName() + "进入等待状态");
                    o.wait();
                } catch (Exception e) {

                }
            }
        }, "线程2");


        Thread thread3 = new Thread(() -> {
            try {
                synchronized (o) {
                    System.out.println("notify()随机唤醒一个,notifyAll()唤醒所有");
                    // o.notify(); //随机唤醒一个,一直阻塞
                    o.notifyAll();//唤醒所有
                }
            } catch (Exception ex) {

            }
        }, "线程3");

        thread1.start();
        thread2.start();
        Thread.sleep(2000);//保证线程1和线程2先运行
        thread3.start();
    }
}
posted @ 2024-08-14 11:24  干饭达人GoodLucy  阅读(10)  评论(0)    收藏  举报