Java项目-ExecutorService
一、线程池: 提供一个线程队列,队列中保存着所有等待状态的线程。避免了创建与销毁的额外开销,提高了响应的速度。
二、线程池的体系结构:
java.util.concurrent.Executor 负责线程的使用和调度的根接口
|--ExecutorService 子接口: 线程池的主要接口
|--ThreadPoolExecutor 线程池的实现类
|--ScheduledExceutorService 子接口: 负责线程的调度
|--ScheduledThreadPoolExecutor : 继承ThreadPoolExecutor,实现了ScheduledExecutorService
三、工具类 : Executors
ExecutorService newFixedThreadPool() : 创建固定大小的线程池
ExecutorService newCachedThreadPool() : 缓存线程池,线程池的数量不固定,可以根据需求自动的更改数量。
ExecutorService newSingleThreadExecutor() : 创建单个线程池。 线程池中只有一个线程
ScheduledExecutorService newScheduledThreadPool() : 创建固定大小的线程,可以延迟或定时的执行任务
创建线程的2种方式,一种是直接继承Thread,另外一种就是实现Runnable接口。
这2种方式都有一个缺陷就是:在执行完任务之后无法获取执行结果。
如果需要获取执行结果,就必须通过共享变量或者使用线程通信的方式来达到效果,这样使用起来就比较麻烦。
而自从Java 1.5开始,就提供了Callable和Future,通过它们可以在任务执行完毕之后得到任务执行结果。
@FunctionalInterface public interface Callable{ //Computes a result, or throws an exception if unable to do so. //@return computed result //@throws Exception if unable to compute a result V call () throws Exception; }Future就是对于具体的Runnable或者Callable任务的执行结果进行取消、查询是否完成、获取结果。
必要时可以通过get方法获取执行结果,该方法会阻塞直到任务返回结果。
Future类位于java.util.concurrent包下,它是一个接口:
public interface Future{ //用来取消任务,如果取消任务成功则返回true,如果取消任务失败则返回false。 //mayInterruptIfRunning表示是否允许取消正在执行却没有执行完毕的任务 boolean cancel(boolean mayInterruptIfRunning); //表示任务是否被取消成功,如果在任务正常完成前被取消成功,则返回 true。 boolean isCancelled(); //表示任务是否已经完成,若任务完成,则返回true; boolean isDone(); //用来获取执行结果,这个方法会产生阻塞,会一直等到任务执行完毕才返回 V get() throws InterruptedException, ExecutionException; //来获取执行结果,如果在指定时间内,还没获取到结果,就直接返回null。 V get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException; }