美文网首页程序员
经典生产者和消费者

经典生产者和消费者

作者: 尉昌达 | 来源:发表于2020-07-10 06:58 被阅读0次

实现一个同步容器,有2个生产者线程,10个消费者线程。

public class MyContainer1<T> {
   final private LinkedList<T> lists = new LinkedList<>();
   final private int MAX = 10; //最多10个元素
   private int count = 0;
   
   
   public synchronized void put(T t) {
       while(lists.size() == MAX) { //这边用while是因为被唤醒的时候,还需要再去判断容器满了没有,其他生产者线程可能先拿到锁把它加满。
           try {
               this.wait(); //effective java
           } catch (InterruptedException e) {
               e.printStackTrace();
           }
       }
       
       lists.add(t);
       ++count;
       this.notifyAll(); //通知消费者线程进行消费
   }
   
   public synchronized T get() {
       T t = null;
       while(lists.size() == 0) {
           try {
               this.wait();
           } catch (InterruptedException e) {
               e.printStackTrace();
           }
       }
       t = lists.removeFirst();
       count --;
       this.notifyAll(); //通知生产者进行生产
       return t;
   }
   
   public static void main(String[] args) {
       MyContainer1<String> c = new MyContainer1<>();
       //启动消费者线程
       for(int i=0; i<10; i++) {
           new Thread(()->{
               for(int j=0; j<5; j++) System.out.println(c.get());
           }, "c" + i).start();
       }
       
       try {
           TimeUnit.SECONDS.sleep(2);
       } catch (InterruptedException e) {
           e.printStackTrace();
       }
       
       //启动生产者线程
       for(int i=0; i<2; i++) {
           new Thread(()->{
               for(int j=0; j<25; j++) c.put(Thread.currentThread().getName() + " " + j);
           }, "p" + i).start();
       }
   }
}

这里是用了notifyAll();会存在一个问题,比如此时容器满了,消费者notifyAll(),可能会被其他消费者拿到锁,然后继续释放锁,通知的不够精确。

下面用Condition来解决:

public class MyContainer2<T> {
    final private LinkedList<T> lists = new LinkedList<>();
    final private int MAX = 10; //最多10个元素
    private int count = 0;
    
    private Lock lock = new ReentrantLock();
    private Condition producer = lock.newCondition();
    private Condition consumer = lock.newCondition();
    
    public void put(T t) {
        try {
            lock.lock();
            while(lists.size() == MAX) { 
                producer.await();
            }
            
            lists.add(t);
            ++count;
            consumer.signalAll(); //通知消费者线程进行消费
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
    
    public T get() {
        T t = null;
        try {
            lock.lock();
            while(lists.size() == 0) {
                consumer.await();
            }
            t = lists.removeFirst();
            count --;
            producer.signalAll(); //通知生产者进行生产
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
        return t;
    }
    
    public static void main(String[] args) {
        MyContainer2<String> c = new MyContainer2<>();
        //启动消费者线程
        for(int i=0; i<10; i++) {
            new Thread(()->{
                for(int j=0; j<5; j++) System.out.println(c.get());
            }, "c" + i).start();
        }
        
        try {
            TimeUnit.SECONDS.sleep(2);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        
        //启动生产者线程
        for(int i=0; i<2; i++) {
            new Thread(()->{
                for(int j=0; j<25; j++) c.put(Thread.currentThread().getName() + " " + j);
            }, "p" + i).start();
        }
    }
}

Condition producer = lock.newCondition();
Condition consumer = lock.newCondition();

相当于new了2个等待队列,一个是producer,一个是consumer。

  • producer.await()的时候是线程进入producer这个等待队列等待。
  • consumer.await()的时候是线程进入consumer这个等待队列等待。
    需要唤醒的时候,producer就可以调用consumer.signalAll(),consumer就调用producer.signalAll()唤醒指定的队列。

相关文章

网友评论

    本文标题:经典生产者和消费者

    本文链接:https://www.haomeiwen.com/subject/lwodcktx.html