高并发缓存实现 二

public class ProductTask {
	private static ConcurrentHashMap<String, Future<Long>> glodDeptFutuMap = new ConcurrentHashMap<String, Future<Long>>();

	public long getValue(final String key) {
		long deptid = 0;
		while (true) {
			Future<Long> deptV = glodDeptFutuMap.get(key);
			if (deptV == null) {
				Callable<Long> eval = new Callable<Long>() {
					public Long call() throws Exception {
						
						long s = new Random().nextLong();
						System.out.println(key+" 新值: "+s+"\t");
						return s;
					}
				};

				FutureTask<Long> ft = new FutureTask<Long>(eval);
				deptV = glodDeptFutuMap.putIfAbsent(key, ft);
				if (deptV == null) {
					deptV = ft;
					ft.run();
				}
			}
			try {
				deptid = deptV.get();
			} catch (InterruptedException e) {
				e.printStackTrace();
			} catch (ExecutionException e) {
				e.printStackTrace();
			}
			break;
		}

		return deptid;
	}

}

 

public class OperProductThread implements Runnable,Serializable{

	private String product ;
	public OperProductThread(String product){
		this.product = product;
	}
	public void run() {
		ProductTask pro = new ProductTask();
		System.out.println(product+"\t"+pro.getValue(product)+" "+Thread.currentThread().getName());
	}
}
 

public class ProductTest {

	public static void main(String[] args) {
		//构造一个线程池 
        ThreadPoolExecutor threadPool = new ThreadPoolExecutor(5, 10, 3, 
        TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(10), 
        new ThreadPoolExecutor.CallerRunsPolicy()); 
        
        for (int i = 1; i <= 2000; i++)
        {
        	threadPool.execute(new OperProductThread("product"+i));
        }
        for (int i = 1; i <= 2000 ; i++)
        {
        	threadPool.execute(new OperProductThread("product"+i));
        }
        
        threadPool.shutdown();
        try {  
            boolean loop = true;  
            do {    //等待所有任务完成  
                loop = !threadPool.awaitTermination(2, TimeUnit.SECONDS);  
            } while(loop);  
        } catch (InterruptedException e) {  
            e.printStackTrace();  
        } 
	}
}
 

 

你可能感兴趣的:(高并发)