Java 线程池——笔记

Java 线程池——笔记

// 线程数
Integer threadNum = 10;
// 初始化线程池
ExecutorService ex = Executors.newFixedThreadPool(threadNum);
// 初始化计数器
CountDownLatch latch = new CountDownLatch(threadNum);
ex.submit(new Runnable() {
	@Override
	public void run() {
		try {
			// 线程代码
			…… 
		} catch (Exception e) {
			e.printStackTrace();
			log.error("入库异常" , e);
		}finally {
			// 线程结束
			latch.countDown();
		}
	}
});
try {
	// 等待全部查询结束
	latch.await();
	// 关闭线程
	ex.shutdown();
} catch (InterruptedException e) {
	e.printStackTrace();
	log.error("关闭线程异常" , e);
}
// 汇总代码
……
List<Callable<Boolean>> threadList = new ArrayList<Callable<Boolean>>();
for (int i = 0; i < 10; i++) {
	threadList.add(new Callable<Boolean>() {
		@Override
		public Boolean call() throws Exception {
			// 线程代码
			…… 
			return true;
		}
	});
}
// 初始化线程池
ExecutorService ex = Executors.newFixedThreadPool(threadList.size());
try {
	List<Future<Boolean>> futureList = ex.invokeAll(threadList);
	for (Future<Boolean> future : futureList) {
  			if (future != null && future.get() != null) {
			// 汇总代码
			……
  			}
	}
} catch (Exception e) {
	e.printStackTrace();
	log.error("线程异常" , e);
} finally {
	// 关闭线程
	ex.shutdown();
}
private static ThreadPoolExecutor threadPoolExecutor;

public void name() {
	if (threadPoolExecutor == null) {
        threadPoolExecutor = new ThreadPoolExecutor(2,
                20, 10, TimeUnit.SECONDS, new LinkedBlockingQueue<>(),
                getRejectedExecutionHandler());
    }
	
	threadPoolExecutor.execute(() -> {
		// 线程代码
		…… 
	});
	
    private RejectedExecutionHandler getRejectedExecutionHandler() {
        return (r, executor) -> {
            try {
                executor.getQueue().put(r);
            } catch (InterruptedException e) {
                log.error("创建线程池失败, error: ", e);
                throw new ServiceException("创建线程池失败");
            }
        };
    }
}
ThreadPoolExecutor threadPoolExecutor = null;
try {
    threadPoolExecutor = new ThreadPoolExecutor(2,
            10, 10, TimeUnit.SECONDS, new LinkedBlockingQueue<>(),
            getRejectedExecutionHandler());
    for (int i = 0; i < 10; i++) {
    	Future<T> data = threadPoolExecutor.submit(() -> {
			// 线程代码
			…… 
    	});
    }
} catch (IOException e) {
	log.error("拨测失败, error: ", e);
} finally {
    if (threadPoolExecutor != null) {
        threadPoolExecutor.shutdown();
    }
}
  • 10
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值