• java----wait/notify


    解释

      wait/notify必须配合synchronized使用

    demo

    class NotifyStop2 {
        private final Object lock = new Object();
    
        public void add(String s) throws InterruptedException {
            Thread.sleep(1000);
            synchronized (lock) {
                System.out.println("add notify qian");
                //唤醒其他线程,但是其他线程不能执行,因为lock这把锁,还是被我占用的
                lock.notify();
                System.out.println("add notify hou");
                try {
                    Thread.sleep(5000);
                    System.out.println("add wait qian");
                    //释放lock锁,其他线程可以执行了【使用wait释放锁,或者方法执行完毕,也是释放锁】
                    lock.wait();
                    System.out.println("add wait hou");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
    
        }
    
        public void get() throws InterruptedException {
            synchronized (lock) {
                try {
                    System.out.println("get wait qian");
                    lock.wait();
                    System.out.println("get wait hou");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("get notify qian");
                lock.notify();
                Thread.sleep(5000);
                System.out.println("get notify hou");
            }
        }
    
        public static void main(String[] args) {
            NotifyStop2 notifyStop2 = new NotifyStop2(); //特别注意使用同一个对象进行调用
            new Thread(() -> {
                try {
                    notifyStop2.add("abc");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }, "t1").start();
            new Thread(() -> {
                try {
                    notifyStop2.get();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }, "t2").start();
        }
    }
    

      

  • 相关阅读:
    关系数据理论
    JavaScript语言——对象
    网络编程基础入门级
    数据库加快查询速度索引
    C/C++随机函数的生成(转载)
    sql连接查询
    深入浅出HTTP请求
    17搜索如何抓全网页
    搜索引擎之百度一下
    搜索引擎之中搜
  • 原文地址:https://www.cnblogs.com/yanxiaoge/p/14375169.html
Copyright © 2020-2023  润新知