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();
                }

            }
        }
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章