一起养成写作习惯!这是我参与「掘金日新计划 · 4 月更文挑战」的第9天,点击查看活动详情。
使用Semaphore创建字符串池
类Semaphore可有效地对并发执行任务的线程数量进行限制,这种功能可应用在pool池技术中,可以设置同时访问pool池中数据的线程数量。
同时有若干个线程可以访问池中的数据,但同时只有一个线程可以取得数据,使用完毕后再放回池中。
字符串池实现代码:
public class ListPool {
private int poolMaxSize = 5;
private int semaphorePermits=5;
private List<String> list = new ArrayList<String>();
private Semaphore semaphore = new Semaphore(semaphorePermits);
private ReentrantLock reentrantLock = new ReentrantLock();
private Condition condition = reentrantLock.newCondition();
public ListPool(){
super();
for (int i = 0; i < poolMaxSize ; i++) {
list.add("ozx"+(i+1));
}
}
public String get(){
String getValue = null;
try {
semaphore.acquire();
reentrantLock.lock();
while(list.size() == 0){
condition.await();
}
getValue = list.remove(0);
reentrantLock.unlock();
semaphore.release();
} catch (InterruptedException e) {
e.printStackTrace();
}
return getValue;
}
public void put(String value){
reentrantLock.lock();
list.add(value);
condition.signalAll();
reentrantLock.unlock();
}
}
复制代码
线程类代码:
@Slf4j
public class ListPoolThread implements Runnable {
private ListPool listPool;
public ListPoolThread(ListPool listPool){
super();
this.listPool=listPool;
}
@Override
public void run() {
for (int i = 0; i < Integer.MAX_VALUE ; i++) {
String getValue = listPool.get();
log.info("线程名:{} 获取的字符串的值:{}",Thread.currentThread().getName(),getValue);
listPool.put(getValue);
}
}
}
复制代码
运行类代码如下:
public class ListPoolTest {
public static void main(String[] args) {
ListPool listPool = new ListPool();
ListPoolThread[] poolThreads = new ListPoolThread[10];
for (int i = 0; i < poolThreads.length ; i++) {
poolThreads[i] = new ListPoolThread(listPool);
}
for (int i = 0; i < poolThreads.length ; i++) {
new Thread(poolThreads[i]).start();
}
}
}
复制代码
运行结果如下:
17:26:28.111 [Thread-5] INFO com.ozx.concurrentprogram.semaphore.entity.ListPoolThread - 线程名:Thread-5 获取的字符串的值:ozx1
17:26:28.111 [Thread-2] INFO com.ozx.concurrentprogram.semaphore.entity.ListPoolThread - 线程名:Thread-2 获取的字符串的值:ozx2
17:26:28.111 [Thread-8] INFO com.ozx.concurrentprogram.semaphore.entity.ListPoolThread - 线程名:Thread-8 获取的字符串的值:ozx5
17:26:28.111 [Thread-7] INFO com.ozx.concurrentprogram.semaphore.entity.ListPoolThread - 线程名:Thread-7 获取的字符串的值:ozx4
17:26:28.111 [Thread-5] INFO com.ozx.concurrentprogram.semaphore.entity.ListPoolThread - 线程名:Thread-5 获取的字符串的值:ozx1
17:26:28.113 [Thread-5] INFO com.ozx.concurrentprogram.semaphore.entity.ListPoolThread - 线程名:Thread-5 获取的字符串的值:ozx1
17:26:28.113 [Thread-5] INFO com.ozx.concurrentprogram.semaphore.entity.ListPoolThread - 线程名:Thread-5 获取的字符串的值:ozx1
复制代码