线程通信wait()和 notify()方法的使用

线程通信

//notify 通知,通告
//lock 锁;水闸,船闸;(机器部件等的)锁定;
/*
wait() 与 notify()
wait():令当前线程挂起并放弃CPU,使别的线程可访问并修改共享资源,而当前线程排队等候再次对资源的访问
notify():唤醒正在排队等待同步资源的线程结束等待
Java.lang.Object提供的这两个方法只有在synchronized方法或synchronized代码块中才能使用,
否则会报java.lang.IllegalMonitorStateException异常
*/
public class TestWaitNotify {
    static  Object lock = new Object();

    public static void main(String[] args) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                synchronized (lock){
                    System.out.println("start execute thread A");
                    try {
                        Thread.sleep(1000);
                        System.out.println("A execute the things one second");

                        System.out.println("A will release lock,into wait");
                        lock.wait();
                        System.out.println("A want to keep doing something ");
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();

        new Thread(new Runnable() {
            @Override
            public void run() {
                synchronized (lock){
                    try {
                        System.out.println("start execute Thread B,B need 3 seconds to do something");
                        Thread.sleep(3000);

                        System.out.println("B do thing in three seconds, then awaken (唤醒)A");
                        lock.notify();
                        System.out.println("B feels uncomfortable and has to do something for two seconds");
                        Thread.sleep(2000);
                        System.out.println("B is about to quit(退出)");
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值