类Semaphore可以有效地对并发执行并发执行任务的线程数量进行限制,这种功能可以应用在pool池技术中,可以设置同时访问pool池中数据的线程数量。
本实验的功能是同时有若干个线程可以访问池中的数据,但同时只有一个线程可以取得数据,使用完毕后再放回池中。
package cn.yu.test;
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;
public class ListPool {
private int poolMaxSize = 3;
private int semaphorePermits = 5;
private List<String> list = new ArrayList<String>();
private Semaphore concurrencySemaphore = new Semaphore(semaphorePermits);
private ReentrantLock lock = new ReentrantLock();
private Condition condition = lock.newCondition();
public ListPool() {
super();
for(int i = 0;i<poolMaxSize;i++) {
list.add("Semaphore"+(i+1));
}
}
public String get() {
String getString = null;
try {
concurrencySemaphore.acquire();
lock.lock();
while(list.size() == 0) {
condition.await();
}
getString = list.remove(0);
lock.unlock();
} catch (InterruptedException e) {
e.printStackTrace();
}
return getString;
}
public void put(String stringValue) {
lock.lock();
list.add(stringValue);
condition.signalAll();
lock.unlock();
concurrencySemaphore.release();
}
}
package cn.yu.test;
public class MyThread extends Thread{
private ListPool listPool;
public MyThread(ListPool listPool) {
super();
this.listPool = listPool;
}
public void run() {
for(int i = 0;i<Integer.MAX_VALUE;i++) {
String getString = listPool.get();
System.out.println(Thread.currentThread().getName()+"取得值"+getString);
listPool.put(getString);
}
}
}
package cn.yu.test;
import java.util.Scanner;
public class Test {
public static void main(String [] args) {
ListPool pool = new ListPool();
MyThread[] threadArray = new MyThread[12];
for(int i =0;i<threadArray.length;i++) {
threadArray[i] = new MyThread(pool);
}
for(int i =0;i<threadArray.length;i++) {
threadArray[i] = new MyThread(pool);
}
for(int i = 0;i<threadArray.length;i++) {
threadArray[i].start();
}
}
}
运行结果:
Thread-2取得值Semaphore1
Thread-7取得值Semaphore1
Thread-5取得值Semaphore3
Thread-6取得值Semaphore3
Thread-6取得值Semaphore3
Thread-6取得值Semaphore3
Thread-6取得值Semaphore3
Thread-6取得值Semaphore3
Thread-6取得值Semaphore3
Thread-6取得值Semaphore3
Thread-6取得值Semaphore3
Thread-6取得值Semaphore3
Thread-2取得值Semaphore3
Thread-7取得值Semaphore1
Thread-11取得值Semaphore2
...............