package com.maven.info.semaphore; import java.util.ArrayList; import java.util.List; import java.util.concurrent.Semaphore; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.ReentrantLock; /** * @program: maventestone * @description: * @author: 18124785 * @create: 2019-02-03 10:38 */ public class ListPoolDemo { /* 可以有效的对并发执行任务的线程数进行限制, 这种功能可以应用在pool线程池技术中, 可以设置同时访问pool池中的数据的线程数量*/ private int poolMaxSize = 3; private int semaphorePermits =5; private List<String> list = new ArrayList<>(); private Semaphore concurrencySemaphore = new Semaphore(10); private ReentrantLock lock = new ReentrantLock(); private Condition condition = lock.newCondition(); public ListPoolDemo(){ for (int i=0;i<poolMaxSize;i++){ list.add("superman_"+i); } } public String get(){ String getString =null; try { concurrencySemaphore.acquire(); lock.lock(); while (list.size()==0){ condition.await(); } getString = list.remove(0); lock.unlock(); }catch (Exception e){ e.printStackTrace(); } return getString; } public void put(String StringValue){ lock.lock(); list.add(StringValue); condition.signalAll(); lock.unlock(); concurrencySemaphore.release(); } }