zoukankan      html  css  js  c++  java
  • 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可能会导致死锁,而notifyAll不会。

  • 相关阅读:
    MYSQL最大连接数设置
    判断闰年
    Hanoi塔问题(递归)
    字符串替换(find函数和replace函数)
    全排列问题(next_permutation函数)
    南阳理工 oj 题目739 笨蛋难题四
    (c++实现)南阳理工 题目325 zb的生日
    (c++实现)南洋理工 oj 267 郁闷的C小加(二)
    (c++实现)南阳理工acm 题目117 求逆序数
    (c++实现) 南洋理工acm 题目2 括号配对问题
  • 原文地址:https://www.cnblogs.com/jarjune/p/10938752.html
Copyright © 2011-2022 走看看