ExecutorService 线程池使用实例

声明:本文纯属个人随手笔记,如果对您有参考价值我十分开心,如果有存在错误,或者有更好的解决办法也麻烦您留言告诉我,大家共同成长,切勿恶言相。 欢迎加入资源共享QQ群:275343679,一起发现知识、了解知识、学习知识、分享知识。网站:www.itlantian.top 

=======================================================================

ExecutorService线程池实例代码如下: 

public static void main(String args[]) throws InterruptedException,ExecutionException {

	long start = System.currentTimeMillis();
	ExecutorService pool = Executors.newFixedThreadPool(10);
	System.out.println("New pool: " + (System.currentTimeMillis() - start));
	List < Future > lf = new ArrayList < Future > (2);
	for (int i = 0; i < 20; i++) {
        //每次放入一个新的对象,避免数据覆盖
		StockDTO stock = new StockDTO();
		stock.setComGoodsSid("NY" + i);
		lf.add(pool.submit(new StockCallable(stock, i)));
	}
	System.out.println("Push pool: " + (System.currentTimeMillis() - start));

	pool.shutdown();
	System.out.println("Down pool: " + (System.currentTimeMillis() - start));
	for (Future f: lf) {
		StockDTO s = (StockDTO) f.get();
		System.out.println(JsonMapper.toJsonString(s));
	}
	System.out.println("list pool: " + (System.currentTimeMillis() - start));

}

static class StockCallable implements Callable < StockDTO > {

	private final StockDTO newStock;
	private int i;

	public StockCallable(StockDTO oldStock, int i) {
		System.out.println("********" + i);
		oldStock.setComSid("CM" + i);
		this.newStock = oldStock;
	}
    
        @Override 
        public StockDTO call() throws Exception {
		//Thread.sleep(100);
		//执行代码
		return newStock;
	}

}

 

你可能感兴趣的:(Java,线程,线程池)