Condition的生产者消费者的实现

这里是要作为Condition实现生产者与消费者的示例代码。要学习Condition的原理与实现,可以看这篇文章 :
https://www.jianshu.com/p/cab88918dde4

//生产者
public class ThreadATest extends Thread{

   private ProdAndCustService prodAndCustService;

   public ThreadATest(ProdAndCustService prodAndCustService) {
       super();
       this.prodAndCustService=prodAndCustService;
   }

   @Override
   public void run() {
       prodAndCustService.set();
   }
}

//消费者
public class ThreadB extends Thread{

   private ProdAndCustService prodAndCustService;

   public ThreadB(ProdAndCustService prodAndCustService) {
       super();
       this.prodAndCustService=prodAndCustService;
   }

   @Override
   public void run() {
       prodAndCustService.get();
   }
}

//生产与消费服务具体实现
public class ProdAndCustService {

   //厨师同时煮饭的人数,生产者
   volatile private Semaphore setSemaphore = new Semaphore(10);

   //消费者,同时吃饭的人
   volatile private Semaphore getSemaphore = new Semaphore(20);

   volatile private ReentrantLock lock = new ReentrantLock();

   volatile private Condition setCondition = lock.newCondition();

   volatile private Condition getCondition = lock.newCondition();
   //定义装产品的盘子只有四个
   volatile private Object[] producePosition = new Object[4];
   
   private boolean isFull() {
       boolean full = true;
       for (int i = 0; i < producePosition.length; i++) {
           if (producePosition[i] == null) {
               full = false;
               break;
           }
       }
       return full;
   }

   private boolean isEmpty() {
       boolean empty = true;
       for (int i = 0; i < producePosition.length; i++) {
           if (producePosition[i] != null) {
               empty = false;
               break;
           }
       }
       return empty;
   }

   /** 生产多个菜*/
   public void set(){

       try{
           //获取允许信号
           setSemaphore.acquire();
           //加锁
           lock.lock();
           while(isFull()) {
//                System.out.println("厨师开始等待等待。。。");
               setCondition.await();
           }

           for(int i=0;i

总共120个线程,分别是厨师60个与客户60个。

你可能感兴趣的:(Condition的生产者消费者的实现)