Java生产者消费者模式

 

package cn.sdut.demo.concurrency;

import java.util.Random;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * Created By Majiatao
 */
public class ProducerConsumerDemo {
   private static int count = 0;
    ReentrantLock lock = new ReentrantLock();
    Condition emptyCondition = lock.newCondition();
    Condition fullCondition = lock.newCondition();

    public static void main(String[] args) {
        ProducerConsumerDemo producerConsumerDemo = new ProducerConsumerDemo();
        new Thread(producerConsumerDemo.new Producer()).start();
        new Thread(producerConsumerDemo.new Consumer()).start();
    }

    class Producer implements Runnable {
        @Override
        public void run() {
            for (int i = 0; i < 20; i++) {
                try {
                    Thread.sleep(new Random().nextInt(2000));

                    lock.lock();
                    while (count == 10) {
                        fullCondition.await();
                    }

                    System.out.println("生产了一个商品,还剩余" + (++count));
                    emptyCondition.signalAll();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    lock.unlock();
                }
            }
        }
    }

    class Consumer implements Runnable {
        @Override
        public void run() {
            for (int i = 0; i < 20; i++) {
                try {
                    Thread.sleep(new Random().nextInt(2000));
                    lock.lock();
                    while (count == 0) {
                        emptyCondition.await();
                    }

                    System.out.println("消费了一个商品,还剩余" + (--count));
                    fullCondition.signalAll();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    lock.unlock();
                }

            }
        }
    }
}

 

你可能感兴趣的:(多线程)