package com.wb.demo.util; import com.graphbuilder.struc.LinkedList; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; public class CommonLock<T> { final private LinkedList list = new LinkedList(); final private int max = 10; private int count=0; private Lock lock = new ReentrantLock(); private Condition producer = lock.newCondition();//本质是调用wait,notfiy时只有一个等待队列 private Condition consumer = lock.newCondition(); public void putEle(T t) { try { lock.lock(); while (list.size() == max) { producer.await();//生产数量等于最大进行等待 } list.addToHead(t);//小于最大数量增加, ++count; consumer.signalAll();//唤醒所有消费者去消费 } catch (InterruptedException e) { e.printStackTrace(); } finally { lock.unlock(); } } public T getEle() { T t = null; try { lock.lock(); while (list.size() == 0) { consumer.await();//消费后数量为零,消费者进行等待 } t = (T) list.removeTail();//有数据继续消费, count--; producer.signalAll();//通知生产者去生产 } catch (Exception e) { e.printStackTrace(); } finally { lock.unlock(); } return t; } public static void main(String[] args) { CommonLock<String> commonLock =new CommonLock(); for (int i = 0; i <10 ; i++) { new Thread(()->{ for (int j = 0; j <5 ; j++) System.out.println(commonLock.getEle()); },"consumer"+i).start(); } try { TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); } for (int i = 0; i < 2; i++) { new Thread(()-> { for (int j = 0; j <25 ; j++) commonLock.putEle(Thread.currentThread().getName()+"_"+j); },"produce"+i).start(); } } }
标签:int,lock,list,private,util,并发,Lock,原理,import From: https://www.cnblogs.com/wangbiaohistory/p/18627111