zoukankan      html  css  js  c++  java
  • 线程协作--wait,notify:经典消费者生产者

    JDK 中关于wait,notify这两个方法的介绍:

      1、wait:导致当前线程等待,直到另一个线程调用该对象的notify()方法或notifyAll()方法。并且释放锁(Thread.sleep()不释放锁)。后续的代码,不执行。

      2、notify:唤醒线程。后续的代码继续执行。

    注意的点:

      1、使用这两个方法,必须拥有对象的监视器。

      2、线程在执行完wait方法后,进入阻塞,释放锁。

      3、执行notify方法后,唤醒执行wait方法的线程,执行wait之后的代码逻辑。

    示例:

     

    import java.util.ArrayList;
    import java.util.List;
    
    public class wait_and_notify {
      public static void main(String[] args) {
        List<Long> lists = new ArrayList<Long>();
        Producer p = new Producer(lists);   //构造方法进行对象的传递,下同
        Consumer c = new Consumer(lists);
        new Thread(p).start();
        new Thread(c).start();
      }
    }
    
    class Producer implements Runnable {
      private long i = 0 ;
      List<Long> lists;
      private Producer producer;
    
      public Producer(List<Long> lists) {
        this.lists = lists;
      }
      @Override
      public void run() {
        while (true){
          synchronized (lists){
            if(lists.size() > 10){
              lists.notifyAll();
              System.out.println("生成者满了");
              try {
                lists.wait();//后续方法不执行了,等到再次获取cpu时间片,才接着输出 "wait invoke"
                System.out.println("wait invoke!"); 
              } catch (InterruptedException e) {
                e.printStackTrace();
              }
            }else{
              lists.add(i++);
              System.out.println("添加:"+i);
            }
          }
        }
      }
    }
    
    class Consumer implements Runnable {
      List<Long> lists;
      public Consumer(List<Long> lists) {
        this.lists = lists;
      }
      @Override
      public void run() {
        while (true){
          synchronized (lists){
            if(lists.size() <= 0){
              lists.notifyAll(); //后续方法继续执行
              System.out.println("消费者空了");
              try {
                lists.wait();
                System.out.println("Consumer wait invoke!");
              } catch (InterruptedException e) {
                e.printStackTrace();
              }
            }else{
              System.out.println(lists.remove(0));
            }
          }
        }
      }
    }
    

      

  • 相关阅读:
    Codeforces Round #650 (Div. 3)
    C. Count Triangles
    A National Pandemic (思维 + 树链剖分模版)
    扫描线专题
    扫描线模版
    莫队模版
    JS设计模式 -- 4种创建型模式
    滑动窗口的最大值 -- 单调队列
    JS链表实现栈和队列
    js数组扁平化的几种实现方式
  • 原文地址:https://www.cnblogs.com/chen--biao/p/9838475.html
Copyright © 2011-2022 走看看