在java中,直接使用线程来异步的执行任务,线程的每次建立与销毁须要必定的计算机资源开销。每一个任务建立一个线程的话,当任务数量多的时候,则对应的建立销毁开销会消耗大量的资源,这种策略最终可能会使处于高负荷状态的应用崩溃。java
Java中的线程,即便工做单元,也是执行机制。从JDK5开始,把工做单元与执行机制分离开来。编程
- 工做单元:Runnable 和 Callable
- 执行机制:Executor 框架
任务服务器
任务的执行
执行机制的核心接口-Executor,以及实现Executor接口的ExecutorService,
Executor框架 中有两个关键类实现了ExecutorService:多线程
ThreadPoolExecutor并发
线程池的实现类,执行被提交的线程、任务(Callable/Runnable 接口的实现类中的run()方法)
ScheduledThreadPoolExecutor框架
给定延迟或按期的执行任务(Callable/Runnable 接口的实现类中的run()方法)、命令。比Timer 更加灵活,强大。
异步执行的结果(返回值)异步
主要成员: ThreadPoolExecutor(线程池)、ScheduldThreadPoolExecutor、Runnable接口、Future<V>接口、Callable<V>接口 以及 Executors工具类。
ThreadPoolExecutor
一般使用Executors 建立,Executors能够建立三种类型的ThreadPoolExecutor:SingleThreadExecuto、FixedThreadPool、CachedThreadPool工具
FixedThreadPool 建立固定线程数,适用于限制当前线程数量时,适用于负载较重的服务器。
Executor建立使用的API:spa
public static ExecutorService newFixedThreadPool(int nThreads); public static ExecutorService newFixedThreadPool(int nThreads, ThreadFactory threadFactory);
SingleThreadExecutor 建立单个线程,任意时间点不会有多个线程是活动的,适用于须要保证顺序执行各任务的时候。
Executors建立API:操作系统
public static ExecutorService newSingleThreadPool(); public static ExecutorService newSingleThreadPool(ThreadFactory threadFactory);
CachedThreadPool 根据须要建立新线程,大小无界的线程池,适用于执行大量短时间的异步任务时,或负载较轻的服务器。
Executors建立API:
public static ExecutorService newCachedThreadPool(); public static ExecutorService newCachedThreadPool(ThreadFactory threadFactory);
ScheduledThreadPoolExecutor
使用Executors工厂类建立,Executors能够建立两种类型的ScheduldThreadPoolExecutor
ScheduledThreadPoolExecutor 包含若干个线程,适用于多个线程执行周期任务,同时限制执行的线程数量。
Executors 建立固定个数线程ScheduledThreadPoolExecutor 的API:
public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize); public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize, ThreadFactory threadFactory);
SingleThreadScheduledExecutor 之包含一个线程,适用于单个后台线程执行定时任务,同时保证顺序执行各个任务。
Executors 建立单个线程SingleScheduledExecutor 的API:
public static ScheduledExecutorService newSingleScheduledExecutor(int corePoolSize); public static ScheduledExecutorService newSingleScheduledExecutor(int corePoolSize, ThreadFactory threadFactory);
Future 接口
与其实现类FutureTask用于表示异步计算的结果。Runnable/Callable接口提交(submit)给ThreadPoolExecutor或者ScheduledThreadPoolExecutor时候,返回值为FutureTask对象、实现类Future接口的对象。
<T> Future<T> submit(Callable<T> task); <T> Future<T> submit(Runnable task, T result); Future<?> submit(Runnable task);
Runnable 和Callable 接口
均可以被线程池执行,Runnable 无返回值,Callable 有返回值。
Runnable能够使用工厂类Executors将其封装为Callble
Executors 对应API以下:
//将返回的Callable对象提交给线程池返回FutureTask对象,调用FutureTask.get(),返回null public static Callable<Object> callable(Runnable task); //同上提交,FutureTask.get(),返回result对象。 public static Callable<Object> callable(Runnable task, T result);
《Java并发编程的艺术》 -方腾飞 魏鹏 程晓明 著