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

你可能感兴趣的:(Java,java,笔记)