return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
60L, TimeUnit.SECONDS,
new SynchronousQueue());
}
由于使用 SynchronousQueue
作为阻塞队列,所以它的特点是:当有空闲线程存活的时候,复用空闲线程,否则去创建新线程。
1.4 newScheduledThreadPool 方法
public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize) {
return new ScheduledThreadPoolExecutor(corePoolSize);
}
public ScheduledThreadPoolExecutor(int corePoolSize) {
super(corePoolSize, Integer.MAX_VALUE, 0, NANOSECONDS,
new DelayedWorkQueue());
}
ScheduledExecutorService
类多用于定时任务的场景。
总结
Executors
方法的本质就是封装 ThreadPoolExecutor
类,创造比较常用额线程池类。
2. Future、FutureTask 和 Callable
在上篇关于 ThreadPoolExecutor
的文章中提到 executre
方法执行 Runnable
任务,同时也提及到 submit
方法。
public Future submit(Callable task)
那么 Future
、FutureTask
和 Callable
有什么用途呢?
2.1 Future
Future
用处就是对于具体的 Runnable
或者 Callable
任务的执行结果进行取消、查询是否完成、获取结果。必要时可以通过 get
方法获取执行结果,该方法会阻塞直到任务返回结果。
public interface Future {
/**
- 尝试取消任务
- 任务已经执行完成、已经被取消或者任务不能取消的状态时会返回false
- 如果返回ture,并且task没有开始,则应该取消不执行。
- 如果任务已经开始了,就由mayInterruptIfRunning参数决定是否打断
*/
boolean cancel(boolean mayInterruptIfRunning);
/**
- 如果在任务执行完成之前调用返回ture
*/
boolean isCancelled();
/**
- 任务完成返回true
*/
boolean isDone();
/**
- 等待执行完成获取结果
- @return the computed result
- @throws CancellationException if the computation was cancelled
- @throws ExecutionException if the computation threw an
- exception
- @throws InterruptedException if the current thread was interrupted
- while waiting
*/
V get() throws InterruptedException, ExecutionException;
/**
- 等待最多 timeout 时间来获取结果,指定时间内没完成获取到结果,返回null
- @param timeout the maximum time to wait
- @param unit the time unit of the timeout argument
- @return the computed result
- @throws CancellationException if the computation was cancelled
- @throws ExecutionException if the computation threw an
- exception
- @throws InterruptedException if the current thread was interrupted
- while waiting
- @throws TimeoutException if the wait timed