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();
    	}
    }
    

      

  • 相关阅读:
    Python——python读取html实战,作业7(python programming)
    Python——python读取html实战,作业7(python programming)
    Python——python读取xml实战,作业6(python programming)
    Python——python读取xml实战,作业6(python programming)
    二分查找(c &amp; c++)
    大型站点技术架构(八)--站点的安全架构
    Android MTP 文件浏览Demo
    HDU2037 事件排序问题
    折腾开源WRT的AC无线路由之路-3
    启动VIP报CRS-1028/CRS-0223致使VIP状态为UNKNOWN故障分析与解决
  • 原文地址:https://www.cnblogs.com/--zz/p/9671119.html
Copyright © 2011-2022 走看看