Java8 CompletionService 处理线程池
public class ThreadChangeDemo {
//创建
private static ThreadPoolExecutor createExecutor(int corePoolSize,
int maximumPoolSize,
int queueCapacity){
return new ThreadPoolExecutor(corePoolSize,
maximumPoolSize,
60,
TimeUnit.SECONDS,
new MyLinkedBlockingQueue<>(queueCapacity),
new NamedThreadFactory("threadName"));
}
//修改
private static void modifyExecutor(ThreadPoolExecutor executor,
int corePoolSize,
int maximumPoolSize,
int queueCapacity){
executor.setCorePoolSize(corePoolSize);
executor.setMaximumPoolSize(maximumPoolSize);
MyLinkedBlockingQueue queue = (MyLinkedBlockingQueue)executor.getQueue();
queue.setCapacity(queueCapacity);
}
//查询
private static void selectExecutor(ThreadPoolExecutor executor){
System.out.println();
System.out.print("线程:" + Thread.currentThread().getName());
System.out.print(",");
System.out.print("核心线程数:" + executor.getCorePoolSize());
System.out.print(",");
System.out.print("最大线程数:" + executor.getMaximumPoolSize());
System.out.print(",");
System.out.print("活动线程数:" + executor.getActiveCount());
System.out.print(",");
System.out.print("当前排队线程数:" + executor.getQueue().size());
System.out.print(",");
System.out.print("队列剩余大小:" + executor.getQueue().remainingCapacity());
System.out.print(",");
System.out.print("队列大小:" + (executor.getQueue().size() + executor.getQueue().remainingCapacity()));
System.out.println();
}
public static void main(String[] args) throws Exception {
//创建
ThreadPoolExecutor executor = createExecutor(2,2,9);
selectExecutor(executor);
//修改
modifyExecutor(executor,10,10,10);
selectExecutor(executor);
//执行
CompletionService<String> completionService = new ExecutorCompletionService<String>(executor);
for(int i = 0; i < 3; i++){
completionService.submit(() -> {
System.out.println(Thread.currentThread().getName() + ":" + "begin");
TimeUnit.SECONDS.sleep(10);
String result = Thread.currentThread().getName() + "-" + "result";
System.out.println(Thread.currentThread().getName() + ":" + "end");
return result;
});
}
for (int i = 0; i < 3; i++) {
String result = completionService.take().get();
System.out.println(result);
}
System.out.println("end");
selectExecutor(executor);
}
}