zoukankan      html  css  js  c++  java
  • 生产者消费者 wait()。 notify()

    public class ThreadDemo3 {
        public static void main(String[] args){
            MyList list = new MyList();
            Productor p1 = new Productor(list);
            Productor p2 = new Productor(list);
            Productor p3 = new Productor(list);
    
            Consumer c1 = new Consumer(list);
    //        Consumer c2 = new Consumer(list);
            p1.start();
            p2.start();
            p3.start();
            c1.start();
    //        c2.start();
        }
    }
    
    
    class MyList {
        private int MAX = 100;
        private java.util.List<Integer> list = new java.util.LinkedList<Integer>();
    
        public synchronized void addList(Integer i) {
            while (list.size() >= MAX) {
                try {
                    wait();// 进入锁对象的 等待序列,同时交出锁的控制权。他是对象的方法。//如果被唤醒,那么会接着执行改方法下面的语句。
                    //Thread.sleep(),sleep 是 Thread 的静态方法,只是让线程暂时休眠,不参与cpu的争夺,他与是否具有锁控制权无关,之前有锁控制权,
                    //那么sleep结束之后,醒来了,依旧有锁的控制权,如果之前就没有锁的控制权,那么醒来之后依旧没有锁的控制权。
                }
                catch (Exception e) {
                }
            }
            list.add(i);
            notify();// 由锁对象随机通知(或者说唤醒?)锁等待序列中的一个线程,告诉他,可以获得锁的控制权了,(然后带着锁控制权去争夺cpu)
            //因为是随机通知等待序列中的某一个,所以,前面不能直接往list中添加东西。必须做一定的处理。
            System.out.println("productor.size======>>>>>>>  "+ list.size());
        }
    
        public synchronized int removeList() {
            while (list.size() == 0) {
                try {
                    wait();
                }
                catch (Exception e) {
                }
            }
            int result = list.remove(0);
            notify();
            System.out.println("customer===>>>>>  "+list.size());
            return result;
         
        }
    }
    
    
    
    
    //生产者
    class Productor extends Thread{
        private static int I = 1;
        private MyList list;
        public Productor(MyList list){
            this.list = list;
        }
        public void run(){
            while(true){
                list.addList(I);
                System.out.println(I);
                I ++;
            }
        }
    }
    
    
    //消费者
    class Consumer extends Thread{
        private int i;
        private MyList list;
        public Consumer(MyList list){
            this.list = list;
        }
        public void run(){
            while(true){
                i = list.removeList();
                System.out.println(i);
            }
        }
    }
    
  • 相关阅读:
    104.Maximum Depth of Binary Tree
    103.Binary Tree Zigzag Level Order Traversal
    102.Binary Tree Level Order Traversal
    101.Symmetric Tree
    100.Same Tree
    99.Recover Binary Search Tree
    98.Validate Binary Search Tree
    97.Interleaving String
    static静态初始化块
    serialVersionUID作用
  • 原文地址:https://www.cnblogs.com/jijizhazha/p/7758136.html
Copyright © 2011-2022 走看看