线程池的状态
ThreadPoolExecutor 使用int的高3位来表示线程池的状态,低29位标识线程数量
状态名 | 高三位 | 接收新任务 | 处理阻塞队列任务 | 说明 |
---|---|---|---|---|
running | 111 | Y | Y | |
shutdown | 000 | N | Y | |
stop | 001 | N | N | |
tidying | 010 | 过度状态,任务全部执行完毕 | ||
terminated | 011 | 终结状态 |
ThreadPoolExecutor的构造方法
ThreadPoolExecutor(int corePoolSize, //核心线程数
int maximumPoolSize, //最大线程数
long keepAliveTime, //救急线程等待时间
TimeUnit unit,//时间单位
BlockingQueue<Runnable> workQueue, //阻塞队列
ThreadFactory threadFactory, //线程工厂,可以为线程创建时取好名字
RejectedExecutionHandler handler//拒绝策略
)
固定大小的线程池
public static ExecutorService newFixedThreadPool(int nThreads) {
return new ThreadPoolExecutor(nThreads, nThreads,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>());
}
单线程线程池
public static ExecutorService newSingleThreadExecutor() {
return new FinalizableDelegatedExecutorService
(new ThreadPoolExecutor(1, 1,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>()));
}
带缓冲线程池
public static ExecutorService newCachedThreadPool() {
return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
60L, TimeUnit.SECONDS,
new SynchronousQueue<Runnable>());
}
submit() : 可以获取执行结果
public static void test4() {
ThreadPoolExecutor pool=(ThreadPoolExecutor) Executors.newFixedThreadPool(2);
Future<String> future = executorService.submit(() -> "ok");
System.out.println("main ==>" + future.get());
}
invokeAll()
List<Future<Object>> futures =
pool.invokeAll(Arrays.asList(() -> "1",
() -> "2",
() -> "3")
);
futures.forEach(f -> System.out.println(f.get()));
invokeAny() 返回一个最先得到结果的任务
Object o = pool.invokeAny(Arrays.asList(() -> "1", () -> "2"));
System.out.println(o);