wait(),notify(),notifyAll()

本文深入解析Java中Object类的wait()与notify()方法,通过实例展示了如何实现线程间的同步。文章包括方法使用、锁获取、线程等待与唤醒等关键概念,并通过代码实现验证了同步机制的有效性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

这3个都是Object的方法,用于线程间的同步。
使用起来很简单。
执行这3个方法都需要先获得监视器的锁。否则会报异常。
在一个线程的锁被notify后,除非它再次获得lock,否则不会执行。

public class Object_Wait_Notify {
    private static Object SYNC_OBJECT = new Object();


    public static void main(String[] args) {

        Thread t1 = new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("t1 is running");
                synchronized (SYNC_OBJECT){
                    System.out.println("t1 got the lock");
                    try {
                        Thread.sleep(200);
                        System.out.println("t1 will wait and release the lock");
                        SYNC_OBJECT.wait();
                        System.out.println("t1 got the monitor again");
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }

                System.out.println("t1 will over");
            }
        });
        t1.start();


        Thread t2 = new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("t2 is running");
                synchronized (SYNC_OBJECT){
                    System.out.println("t2 got the lock and run");
                    System.out.println("t2 notify t1,but t1 will not run unless it got the lock");
                    SYNC_OBJECT.notify();
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println("t2 release the lock");
                }

                System.out.println("t2 will over");

            }
        });
        t2.start();
    }
}

输出:
t1 is running
t1 got the lock
t2 is running
t1 will wait and release the lock
t2 got the lock and run
t2 notify t1,but t1 will not run unless it got the lock
t2 release the lock
t2 will over
t1 got the monitor again
t1 will over


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值