- 线程池
- ThreadPoolExecutor
- 线程
- Callable
- 示例
- 使用线程
- 不使用线程
ExecutorService EXECUTOR = new ThreadPoolExecutor(10, 20, 30L, TimeUnit.SECONDS,
new LinkedBlockingQueue<>(1024), ThreadFactoryBuilder.create().setNamePrefix("Bind-Executor-").build());
param1:核心线程数
param:2:最大线程数
param3:闲置时间(到达闲置时间自动关闭线程)
param4:闲置时间单位
param5:等待缓存区
param6:创建一个新线程
public static class DemoThread implements Callable示例 使用线程{ private Integer total; DemoThread(Integer total){ this.total = total; } @Override public Integer call() throws Exception { Thread.sleep(1000); return total += 1; } }
public static void test() throws ExecutionException, InterruptedException {
long start = System.currentTimeMillis();
LinkedList> futures = new LinkedList<>();
LinkedList result = new LinkedList<>();
for (int i = 0; i < 100; i++) {
Future submit = EXECUTOR.submit(new DemoThread(i));
futures.add(submit);
}
for (Future f : futures){
while (true){
if(f.isDone() && !f.isCancelled()){
result.add(f.get());
break;
}
}
}
System.out.println("test:" + result.toString());
EXECUTOR.shutdown();
System.out.println("test:" + "运行时长" + (System.currentTimeMillis() - start) + "ms");
}
结果:
public static void test2() throws InterruptedException {
long start = System.currentTimeMillis();
LinkedList result = new LinkedList<>();
for (int i = 0; i < 100; i++) {
int bi = i + 1;
Thread.sleep(1000);
result.add(bi);
}
System.out.println("test2:" + result.toString());
System.out.println("test2:" + "运行时长" + (System.currentTimeMillis() - start) + "ms");
}
结果:



