简易对象池
简易的对象池,需要深入了解的话,得阅读<<Thinking in Pattern>>
import java.util.*; import java.util.concurrent.*; /** * 对象池 * @author Administrator * * @param <T> */ class Pool<T>{ private int size; private List<T> items = new ArrayList<T>(); private volatile boolean[] isCheckedOut; Semaphore signalControl; public Pool(int size,Class<T> classObject) { signalControl = new Semaphore(size,true); this.size = size; isCheckedOut = new boolean[size]; for(int i=0;i<size;i++) { try { items.add(classObject.getDeclaredConstructor().newInstance()); }catch (Exception e) { throw new RuntimeException(e); } } } public void checkIn(T x) { if(releaseItem(x)) { signalControl.release(); } } public T checkOut() throws InterruptedException { signalControl.acquire(); return getItem(); } public synchronized T getItem() { for(int i=0;i<size;i++) { if(!isCheckedOut[i]) { isCheckedOut[i] = true; return items.get(i); } } return null; } public synchronized boolean releaseItem(T item) { int index = items.indexOf(item); if(index == -1) return false; if(isCheckedOut[index]) { isCheckedOut[index] = false; return true; } return false; } } class Fat{ private volatile double d; private static int counter = 0; private final int id = counter++; public Fat() { //构建花费昂贵 for(int i=1;i<10000;i++) { d += (Math.PI + Math.E); } } public void operation() { System.out.println(this); } public String toString() { return "Fat id: " + id; } } class CheckoutTask<T> implements Runnable{ private static int counter = 0; private final int id = counter++; private Pool<T> pool; public CheckoutTask(Pool<T> pool) { this.pool = pool; } public void run() { try { T item = pool.checkOut(); System.out.println("Check out " + item); TimeUnit.SECONDS.sleep(1); System.out.println("Check in " + item); pool.checkIn(item); }catch (InterruptedException e) { } } public String toString() { return "CheckTase " + id + " "; } } public class Restaurant{ final static int SIZE = 25; public static void main(String[] args) throws Exception { //创建一个对象池 final Pool<Fat> fatPool = new Pool<Fat>(SIZE, Fat.class); ExecutorService executorService = Executors.newCachedThreadPool(); for(int i=0;i<SIZE;i++) { executorService.execute(new CheckoutTask<Fat>(fatPool)); } System.out.println("All CheckoutTask created"); List<Fat> list = new ArrayList<>(); for(int i=0;i<SIZE;i++) { Fat fat = fatPool.checkOut(); System.out.println(i + ": main() thread check out"); fat.operation(); list.add(fat); } Future<?> blocked = executorService.submit(new Runnable() { @Override public void run() { // TODO Auto-generated method stub try { System.out.println("Is leave out?"); fatPool.checkOut(); }catch (Exception e) { System.out.println("NO"); } } }); TimeUnit.SECONDS.sleep(2); blocked.cancel(true); for(Fat fat:list) { fatPool.checkIn(fat); } for(Fat fat:list) { fatPool.checkIn(fat); } executorService.shutdown(); } }
版权声明:本文为--zz原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。