异步任务执行服务的基础接口:
简介:
之前的介绍中,线程Thread即表示要执行的任务,又表示执行的机制。Java并发包提供了一套框架,大大简化了执行异步任务所需要的开发。框架引入了"执行服务"的概念。它将’任务提交’和’任务的执行’相分离,'执行服务’封装了所有执行的细节,对于任务提交者而言,它可以关注于任务本身,如提交任务,获取结果,取消任务。而不需要关注任务执行的细节,如线程创建,任务调度,线程关闭。
一、Runnable和Callable:
表示要执行的异步任务。Runnable没有返回结果不会抛出异常,而Callable有结果会抛出异常。
//函数式接口,无返回值,且不抛出异常
@FunctionalInterface
public interface Runnable {
void run();
}
//函数式接口,有返回值,抛出异常
@FunctionalInterface
public interface Callable<V> {
V call() throws Exception;
}
二、Executor和ExecutorService:
表示执行任务。
//Executor 接口只有一个执行方法execute。
public interface Executor {
void execute(Runnable var1);
}
//ExecutorService接口在Executor基础上进行了扩展
public interface ExecutorService extends Executor {
//不接受新任务了,已提交的任务还是会执行
void shutdown();
//不接受新任务了,还会终止已提交的任务,已经在运行的任务,也会调用interrupt尝试中断,会返回提交未执行的任务列表。
List<Runnable> shutdownNow();
//shutdown 不会阻塞等待,它们返回不代表所有任务都结束,但isShutDown()会返回 true;
boolean isShutdown();
//判断所有任务是否都执行完毕
boolean isTerminated();
//限制时间等待所有任务结束,如果在时间内都结束了,返回true,否则false
boolean awaitTermination(long var1, TimeUnit var3) throws InterruptedException;
//可以提交带返回值的任务
<T> Future<T> submit(Callable<T> var1);
//提交一个没返回值的任务,同时提供一个结果参数,在异步任务结束前返回。
<T> Future<T> submit(Runnable var1, T var2);
//提交一个没有返回值的任务
Future<?> submit(Runnable var1);
//等待提交列表的任务全部完成
<T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> var1) throws InterruptedException;
//在指定的时间等待列表任务完成,超时没完成的任务会被取消
<T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> var1, long var2, TimeUnit var4) throws InterruptedException;
//只要任务列表有一个完成,其他任务全部取消
<T> T invokeAny(Collection<? extends Callable<T>> var1) throws InterruptedException, ExecutionException;
//指定时间内列表内有一个任务完成,其他任务都取消,没有任务完成抛出超时异常
<T> T invokeAny(Collection<? extends Callable<T>> var1, long var2, TimeUnit var4) throws InterruptedException, ExecutionException, TimeoutException;
}
三、Future:
表示异步任务结果。
public interface Future<V> {
//取消任务,如果任务已完成、或已取消、或某种语言不能取消则返回false,否则返回true.如果未执行,则不执行了。如果任务在运行,传入的var1是true,则调用interrupt尝试打断。
boolean cancel(boolean var1);
//表示任务是否被取消,只要cancel返回true,isCanceled()都会返回true
boolean isCancelled();
//表示线程是否结束
boolean isDone();
//获取异步任务执行的最终结果,未执行完则会阻塞等待。get获取到的三种结果:
//(1)正常完成,get返回正常结果。任务是Runnable,且没有提供结果参数,则返回null.
//(2)任务执行抛出了异常,则get会将异常封装为ExecutionException异常抛出
//(3)任务被取消会抛出CancellationException,被中断则抛出中断异常。
V get() throws InterruptedException, ExecutionException;
//获取异步执行结果,如果未执行完,则阻塞等待指定时间,超时未结束,则抛出超时异常
V get(long var1, TimeUnit var3) throws InterruptedException, ExecutionException, TimeoutException;
}
基本实现原理:
public class Task implements Callable<Integer> {
@Override
public Integer call() throws Exception {
int sleepSeconds = new Random().nextInt(100);
Thread.sleep(sleepSeconds);
return sleepSeconds;
}
public static void main(String[] args) throws InterruptedException, ExecutionException {
//通过工厂类Executors生成一个任务执行服务类,
ExecutorService executor = Executors.newSingleThreadExecutor();
Future<Integer> future = executor.submit(new Task());
}
}
//通过这个方法可以得知,ExecutorService的具体执行实现类是ThreadPoolExecutor 线程池类。线程核心线程只有一个,无界任务队列。
public static ExecutorService newSingleThreadExecutor() {
return new Executors.FinalizableDelegatedExecutorService(new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue()));
}
//下面来看submit()方法
//AbstractExecutorService 是ExecutorService 的抽象类子类,而ThreadPoolExecutor是AbstractExecutorService 的子类。
public abstract class AbstractExecutorService implements ExecutorService {
public <T> Future<T> submit(Callable<T> task) {
if (task == null) {
throw new NullPointerException();
} else {
//是传过来的Runnable任务类转为Callable任务类。
RunnableFuture<Void> ftask = this.newTaskFor(task, (Object)null);
this.execute(ftask);
return ftask;
}
}
}
//RunnableFuture 实现了Runnable接口和Future接口
public interface RunnableFuture<V> extends Runnable, Future<V> {
void run();
}
protected <T> RunnableFuture<T> newTaskFor(Callable<T> callable) {
return new FutureTask(callable);
}
//FutureTask实现了RunnableFuture接口
public class FutureTask<V> implements RunnableFuture<V> {
public FutureTask(Runnable runnable, V result) {
//进行任务类装换
this.callable = Executors.callable(runnable, result);
this.state = 0;
}
}
public static <T> Callable<T> callable(Runnable task, T result) {
if (task == null) {
throw new NullPointerException();
} else {
//runnable 任务类适配
return new Executors.RunnableAdapter(task, result);
}
}
private static final class RunnableAdapter<T> implements Callable<T> {
private final Runnable task;
private final T result;
RunnableAdapter(Runnable task, T result) {
this.task = task;
this.result = result;
}
public T call() {
this.task.run();
return this.result;
}
//在看execute()方法,具体执行的是ThreadPoolExecutor的execute()方法
public class ThreadPoolExecutor extends AbstractExecutorService {
public void execute(Runnable command) {
if (command == null) {
throw new NullPointerException();
} else {
int c = this.ctl.get();
if (workerCountOf(c) < this.corePoolSize) {
//添加工作任务,启动线程
if (this.addWorker(command, true)) {
return;
}
c = this.ctl.get();
}
if (isRunning(c) && this.workQueue.offer(command)) {
int recheck = this.ctl.get();
if (!isRunning(recheck) && this.remove(command)) {
this.reject(command);
} else if (workerCountOf(recheck) == 0) {
this.addWorker((Runnable)null, false);
}
} else if (!this.addWorker(command, false)) {
this.reject(command);
}
}
}
//查看addworker()方法
private boolean addWorker(Runnable firstTask, boolean core) {
int c = this.ctl.get();
label247:
while(!runStateAtLeast(c, 0) || !runStateAtLeast(c, 536870912) && firstTask == null && !this.workQueue.isEmpty()) {
while(workerCountOf(c) < ((core ? this.corePoolSize : this.maximumPoolSize) & 536870911)) {
if (this.compareAndIncrementWorkerCount(c)) {
boolean workerStarted = false;
boolean workerAdded = false;
ThreadPoolExecutor.Worker w = null;
try {
//获取到工作类
w = new ThreadPoolExecutor.Worker(firstTask);
Thread t = w.thread;
if (t != null) {
ReentrantLock mainLock = this.mainLock;
mainLock.lock();
try {
int c = this.ctl.get();
if (isRunning(c) || runStateLessThan(c, 536870912) && firstTask == null) {
if (t.getState() != State.NEW) {
throw new IllegalThreadStateException();
}
this.workers.add(w);
workerAdded = true;
int s = this.workers.size();
if (s > this.largestPoolSize) {
this.largestPoolSize = s;
}
}
} finally {
mainLock.unlock();
}
if (workerAdded) {
//启动任务执行线程
t.start();
workerStarted = true;
}
}
} finally {
if (!workerStarted) {
this.addWorkerFailed(w);
}
}
return workerStarted;
}
c = this.ctl.get();
if (runStateAtLeast(c, 0)) {
continue label247;
}
}
return false;
}
return false;
}
}
//工作类
private final class Worker extends AbstractQueuedSynchronizer implements Runnable {
private static final long serialVersionUID = 6138294804551838833L;
final Thread thread;
Runnable firstTask;
volatile long completedTasks;
Worker(Runnable firstTask) {
this.setState(-1);
this.firstTask = firstTask;
//通过线程工厂创建线程。
this.thread = ThreadPoolExecutor.this.getThreadFactory().newThread(this);
}
//线程启动后,执行ThreadPoolExecutor的run方法
public void run() {
//执行线程池的工作方法
ThreadPoolExecutor.this.runWorker(this);
}
final void runWorker(ThreadPoolExecutor.Worker w) {
Thread wt = Thread.currentThread();
Runnable task = w.firstTask;
w.firstTask = null;
w.unlock();
boolean completedAbruptly = true;
try {
while(task != null || (task = this.getTask()) != null) {
w.lock();
if ((runStateAtLeast(this.ctl.get(), 536870912) || Thread.interrupted() && runStateAtLeast(this.ctl.get(), 536870912)) && !wt.isInterrupted()) {
wt.interrupt();
}
try {
this.beforeExecute(wt, task);
try {
//调用FutureTask的run方法
task.run();
this.afterExecute(task, (Throwable)null);
} catch (Throwable var14) {
this.afterExecute(task, var14);
throw var14;
}
} finally {
task = null;
++w.completedTasks;
w.unlock();
}
}
completedAbruptly = false;
} finally {
this.processWorkerExit(w, completedAbruptly);
}
}
//FutureTask的run 方法,为啥会调用到这个方法呢,是因为FutureTask实现了Runnable接口。因为Runnable都转为了Callable,所以最终调用的是call方法
public void run() {
if (this.state == 0 && RUNNER.compareAndSet(this, (Void)null, Thread.currentThread())) {
boolean var9 = false;
try {
var9 = true;
Callable c = this.callable;
if (c != null) {
if (this.state == 0) {
Object result;
boolean ran;
try {
//执行自定义的业务call方法。
result = c.call();
ran = true;
} catch (Throwable var10) {
result = null;
ran = false;
this.setException(var10);
}
if (ran) {
this.set(result);
var9 = false;
} else {
var9 = false;
}
} else {
var9 = false;
}
} else {
var9 = false;
}
} finally {
if (var9) {
this.runner = null;
int s = this.state;
if (s >= 5) {
this.handlePossibleCancellationInterrupt(s);
}
}
}
this.runner = null;
int s = this.state;
if (s >= 5) {
this.handlePossibleCancellationInterrupt(s);
}
}
}
@Override
public Integer call() throws Exception {
int sleepSeconds = new Random().nextInt(100);
Thread.sleep(sleepSeconds);
return sleepSeconds;
}
}
总结:
异步任务执行服务类将任务的提交和任务的执行给相分离了,任务提交者只需要关注提交任务,获取结果,取消任务。而不需要关注线程的创建,任务调度,线程关闭。极大的简化了开发者的工作量。