Object中wait()、notify()、notifyAll()

Object中wait()、notify()、notifyAll()

解释

必须在synchronized修饰的方法/代码块中使用。

wait()

将当前线程持有对象的锁交出(允许其他线程持有),并进入等待状态。

notify()

唤醒某一个正在等待的线程(由某一个正在等待的线程获取锁)。

notifyAll()

通知所有正在等待的线程(所有正在等待的线程争夺一个锁),由jvm决定唤醒哪一个。

例子

并不是立即唤醒,而是等待被synchronized修饰的代码执行完,释放锁之后才执行,具体看下面demo

public class TestObject {

    public static Object o = new Object();

    public static void main(String[] args) throws InterruptedException {
        Thread thread1 = new MyThread1();
        Thread thread2 = new MyThread2();

        thread1.start();

        Thread.sleep(2000);

        thread2.start();
    }

    static class MyThread1 extends Thread {

        @Override
        public void run() {
            System.out.println("1 >>>> 输出A1");
            synchronized (o) {
                System.out.println("2 >>>> 输出A2");
                try {
                    o.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("6 >>>> 输出A3");
            }
            System.out.println("7 >>>> 输出A4");
        }
    }

    static class MyThread2 extends Thread {

        @Override
        public void run() {
            System.out.println("3 >>>> 输出B1");
            synchronized (o) {
                System.out.println("4 >>>> 输出B2");
                o.notify();
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("5 >>>> 输出B3");
            }
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("8 >>>> 输出B4");
        }
    }
}

输出结果

1 >>>> 输出A1
2 >>>> 输出A2
3 >>>> 输出B1
4 >>>> 输出B2
5 >>>> 输出B3
6 >>>> 输出A3
7 >>>> 输出A4
8 >>>> 输出B4

思考?同样是唤醒一个线程,notify()与notifyAll()有什么区别?

这个时候就要说到锁池等待池了。

  • 锁池:通过notify方法能将等待该对象的某一个线程进入锁池,而notityAll方法能将等待该对象的所有线程都进入锁池。
  • 等待池:通过调用wait方法能将当前线程进入等待池。

在锁池里的线程才有资格争夺锁。
所以notify可能会导致死锁,而notify不会。

posted @ 2019-05-28 17:22 jarjune 阅读( ...) 评论( ...) 编辑 收藏
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值