zoukankan      html  css  js  c++  java
  • 简易对象池

    简易的对象池,需要深入了解的话,得阅读<<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();
    	}
    }
    

      

  • 相关阅读:
    C++-蓝桥杯-小数第n位[除法模拟]
    C++-蓝桥杯-合成植物[并查集][模板题]
    Overleaf操作
    三维向量差积,以及应用
    C++-蓝桥杯-分考场[2017真题][搜索][无向图染色]
    C++-POJ1094-Sorting It All Out[拓扑排序][邻接矩阵]
    C++-LUOGU1059-明明的随机数[堆排序]
    C++-快速排序[STL][快速排序][并归排序][堆排序]
    C++-蓝桥杯-波动数组[2014真题][DP优化]
    C++-蓝桥杯-[T1~T3][结果填空题][2015真题][水题]
  • 原文地址:https://www.cnblogs.com/--zz/p/9671119.html
Copyright © 2011-2022 走看看