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