1、线程池常用接口介绍

1.1、Executor

1
2
3
public interface Executor {
void execute(Runnable command);
}

执行提交的Runnable任务。其中的execute方法在将来的某个时候执行给定的任务,该任务可以在新线程、池化线程或调用线程中执行,具体由Executor的实现者决定。

1.2、ExecutorService

ExecutorService继承自Executor,下面挑几个方法介绍:

1.2.1、shutdown()
1
void shutdown();

启动有序关闭线程池,在此过程中执行先前提交的任务,但不接受任何新任务。如果线程池已经关闭,调用此方法不会产生额外的效果。此方法不等待以前提交的任务完成执行,可以使用awaitTermination去实现。

1.2.2、shutdownNow()
1
List<Runnable> shutdownNow();

尝试停止所有正在积极执行的任务, 停止处理等待的任务,并返回等待执行的任务列表。 此方法不等待以前提交的任务完成执行,可以使用awaitTermination去实现。除了尽最大努力停止处理积极执行的任务外,没有任何保证。例如,典型的实现是:通过Thread#interrupt取消任务执行,但是任何未能响应中断的任务都可能永远不会终止。

1.2.3、isShutdown()
1
boolean isShutdown();

返回线程池关闭状态。

1.2.4、isTerminated()
1
boolean isTerminated();

如果关闭后所有任务都已完成,则返回 true。注意,除非首先调用了shutdown或shutdownNow,否则isTerminated永远不会返回true。

1.2.5、awaitTermination(long timeout, TimeUnit unit)
1
2
boolean awaitTermination(long timeout, TimeUnit unit)
throws InterruptedException;

线程阻塞阻塞,直到所有任务都在shutdown请求之后执行完毕,或者超时发生,或者当前线程被中断(以先发生的情况为准)。

1.2.6、submit
1
<T> Future<T> submit(Callable<T> task);

提交一个value-returning任务以执行,并返回一个表示该任务未决结果的Future。 Future的 get方法将在成功完成任务后返回任务的结果。

1.3、ScheduledExecutorService

安排命令在给定的延迟之后运行,或者定期执行,继承自ExecutorService接口由以下四个方法组成:

1
2
3
4
5
6
7
8
9
10
//在给定延迟之后启动任务,返回ScheduledFuture
public ScheduledFuture<?> schedule(Runnable command,long delay, TimeUnit unit);
public <V> ScheduledFuture<V> schedule(Callable<V> callable,long delay, TimeUnit unit);
//创建并执行一个周期性操作,该操作在给定的初始延迟之后首次启动,然后在给定的周期内执行;
//如果任务的任何执行遇到异常,则禁止后续执行。否则,任务只会通过执行器的取消或终止而终止。
//如果此任务的任何执行时间超过其周期,则后续执行可能会延迟开始,但不会并发执行。
public ScheduledFuture<?> scheduleAtFixedRate(Runnable command,long initialDelay,long period,TimeUnit unit);
//创建并执行一个周期性操作,该操作在给定的初始延迟之后首次启动,然后在一次执行的终止和下一次执行的开始之间使用给定的延迟。
//如果任务的任何执行遇到异常,则禁止后续执行。否则,任务只会通过执行器的取消或终止而终止。
public ScheduledFuture<?> scheduleWithFixedDelay(Runnable command,long initialDelay,long delay,TimeUnit unit);

1.4、ThreadFactory

1
2
3
public interface ThreadFactory {
Thread newThread(Runnable r);
}

按需创建新线程的对象。

1.5、Callable

1
2
3
4
@FunctionalInterface
public interface Callable<V> {
V call() throws Exception;
}

返回任务结果也可能抛出异常。

1.6、Future

1
2
3
4
5
6
public interface Future<V> {
boolean cancel(boolean mayInterruptIfRunning);
boolean isCancelled();
boolean isDone();
V get() throws InterruptedException, ExecutionException;
V get(long timeout, TimeUnit unit)throws InterruptedException, ExecutionException, TimeoutException;

Future表示异步计算的结果。方法用于检查计算是否完成,等待计算完成并检索计算结果。
只有当计算完成时,才可以使用方法get检索结果,如果需要,可以阻塞,直到准备好为止。
取消由cancel方法执行。还提供了其他方法来确定任务是否正常完成或被取消。一旦计算完成,就不能取消计算。

1.7、Delayed

1
2
3
4
public interface Delayed extends Comparable<Delayed> {
//在给定的时间单位中返回与此对象关联的剩余延迟
long getDelay(TimeUnit unit);
}

一种混合风格的接口,用于标记在给定延迟之后应该执行的对象。

1.8、ScheduledFuture

1
public interface ScheduledFuture<V> extends Delayed, Future<V> {}