前言
上一篇【Java 线程知识笔记 (一) Thread与Runnable】中说了Thead类和Runnable接口的使用区别,线程的生命周期等等,最后说到了Callable接口,通过这个接口我们可以实现一个有返回值的线程调用,虽然是有返回值但是返回值要用Future接口去取,这个就是一个异步的过程了。因此本篇就会主要说说Callable接口和Future接口。更多线程知识内容请点击【Java 多线程和锁知识笔记系列】
Callable接口
Thread类和Runnable接口中run ()
方法都没有返回值,而Callable接口是可以有返回值的,首先我们看下Callable接口长什么样子。
@FunctionalInterface
public interface Callable<V> {
/**
* 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;
}
里面只有一个方法call()
,但是这个接口和里面的方法都使用了一个Java 1.5以后的一个特性 – 泛型。也就是说这个返回可以适配多个类型,并且call()
返回的就是我们实现Callable接口时指定的泛型,比如我们要返回String类型。
public class Callable1 implements Callable<String> {
@Override
public String call() throws Exception {
return "This is Callable1";
}
}
当调用call()方法的时候就可以接收返回结果,那么怎么调用call()呢?此时就需要用到Java里面定义的另一个接口Future了。
Future接口
public interface Future<V> {
/**
* 试图取消一个线程的执行,可能会打断正在执行的线程
*/
boolean cancel(boolean mayInterruptIfRunning);
/**
* 判断一个线程是否被取消了。返回true说明,这个线程在完成之前就被取消了
*/
boolean isCancelled();
/**
* 判断一个线程是否完成了。返回true说明,此线程已经执行完毕。
*/
boolean isDone();
/**
* 拿到线程的返回值,如果线程没有执行完,则会阻塞等待线程完毕。
*/
V get() throws InterruptedException, ExecutionException;
/**
* 同上,但是这个能够设置超时时间,当对时间比较敏感的时候,可以通过设置超市时间放弃当前结果。
*/
V get(long timeout, TimeUnit unit)
throws InterruptedException, ExecutionException, TimeoutException;
}
Future接口是一个异步接口,其中有操作线程相关的方法,它可以对线程进行判断或者操作一个线程是否完成,是否取消等等。我们拿到Callable.call()
返回值,就是使用的其中的get()
方法拿到的。既然Future是一个接口,那么就必须使用它的实现类去完成这个动作,Java也同样给我们提供了这样一个实现类FutureTask使用。
FutureTask类
首先先看下FutureTask类的集成关系,它实现了RunnableFuture接口,然后RunnableFuture接口又继承了Runnable和Future。因此FutureTask类既可以获取到相关的方法去拿到返回值。
继承关系
public class FutureTask<V> implements RunnableFuture<V> { ...... }
public interface RunnableFuture<V> extends Runnable, Future<V> { ...... }
那么如何去调用呢?下面用一个小例子展示一下。
public class Callable1 implements Callable<String> {
@Override
public String call() throws Exception {
return "This is Callable1";
}
public static void main(String[] args) throws ExecutionException, InterruptedException {
FutureTask<String> task=new FutureTask<>(new Callable1());
new Thread(task).start(); //借助Thread启动,也可以用线程池,这个以后再说
System.out.println(task.get());
}
}
输出结果
This is Callable1
上面的例子成功的输出了我们在call()方法里预设的内容,由于FutureTask里面没有start()
方法,因此也必须借用Thread类启动,但是直接调用get()
方法为什么可以启动call()
方法呢?这里需要去看源码去理解这块内容了,但是涉及到线程无论多牛逼,最终都是要回到run()
方法的,既然FutureTask实现了Runnable接口,那么它一定也有run()
方法,所以按照这个逻辑,我们去它的run()
方法里看看里面写了什么。
public void run() {
if (state != NEW ||
!UNSAFE.compareAndSwapObject(this, runnerOffset,
null, Thread.currentThread()))
//判断NEW或者CAS,CAS内容很多,以后再说
return;
try {
Callable<V> c = callable; //立刻构造了一个Callable对象
if (c != null && state == NEW) {
V result;
boolean ran;
try {
result = c.call(); //这里调用call方法,并给result赋值
ran = true; //设置flag条件
} catch (Throwable ex) {
result = null;
ran = false;
setException(ex);
}
if (ran) //通过条件
set(result); //调用set方法赋值
}
} finally {
// runner must be non-null until state is settled to
// prevent concurrent calls to run()
runner = null;
// state must be re-read after nulling runner to prevent
// leaked interrupts
int s = state;
if (s >= INTERRUPTING)
handlePossibleCancellationInterrupt(s);
}
}
进来了以后首先判断状态,如果状态不是NEW说明当前线程已经被执行过,或者被取消了,直接返回。如果是NEW
然后就在try
块里面使用全局变量callable
构造一个Callable对象。而全局变量callable
则是通过构造方法传递进来的,在我们的例子里就是new Callable1()
。紧接着如果通过if (c != null && state == NEW)
条件,那么就直接调用 result = c.call()
方法并赋值给result
,而后对标志变量ran
赋值为true
。接着走到最后if (ran)
里面把result
通过setter
方法赋值。
FutureTask#set
protected void set(V v) {
if (UNSAFE.compareAndSwapInt(this, stateOffset, NEW, COMPLETING)) {
outcome = v;
UNSAFE.putOrderedInt(this, stateOffset, NORMAL); // final state
finishCompletion();
}
}
在setter
方法里,其实就是一个CAS进行的状态修改,从NEW
修改为COMPLETING
,然后把结果赋值给全局变量outcome
,并且设置线程最终的状态为NORMAL
,完成本次执行。最终通过finishCompletion()
方法通知所有其他线程,当前线程已经执行完毕,并且把callable
置为空。
/**注意这里的注释
* Removes and signals all waiting threads, invokes done(), and
* nulls out callable.
*/
private void finishCompletion() {
// assert state > COMPLETING;
for (WaitNode q; (q = waiters) != null;) {
if (UNSAFE.compareAndSwapObject(this, waitersOffset, q, null)) {
for (;;) {
Thread t = q.thread;
if (t != null) {
q.thread = null;
LockSupport.unpark(t);
}
WaitNode next = q.next;
if (next == null)
break;
q.next = null; // unlink to help gc
q = next;
}
break;
}
}
done();//这里是个空方法,可能为以后优化使用
callable = null; // callable置空to reduce footprint
}
FutureTask#get
返回值设定完毕,剩下的就要去拿了,转到get()
方法里。
public V get() throws InterruptedException, ExecutionException {
int s = state;
if (s <= COMPLETING) //判断线程是否为完成状态
s = awaitDone(false, 0L); //等待完成(阻塞)
return report(s);//否则直接返回
}
相对于setter
方法,getter
方法稍微简单一些。首先获取当前线程状态,然后if (s <= COMPLETING)
判断线程是否为完成状态,如果没有完成,等待线程完成。如果已经完成,则调用report(s)
方法,把之前设置的outcome
变量里的内容返回出去。
private V report(int s) throws ExecutionException {
Object x = outcome;
if (s == NORMAL) //如果是正常结束状态
return (V)x; //返回
if (s >= CANCELLED) //如果是取消状态,抛出异常
throw new CancellationException();
throw new ExecutionException((Throwable)x); //其他状态也抛出异常
}
awaitDone()
这个方法是阻塞的方法,如何判断等待一个线程完成呢?其实就是在方法里自旋,直到发现状态为完成状态为止。
private int awaitDone(boolean timed, long nanos)
throws InterruptedException {
final long deadline = timed ? System.nanoTime() + nanos : 0L;
WaitNode q = null;
boolean queued = false;
for (;;) { //使用for循环空转,不同的条件进行不同的操作
if (Thread.interrupted()) {
removeWaiter(q);
throw new InterruptedException();
}
int s = state; //不断地获取当前线程状态,并进行判断
if (s > COMPLETING) { //大于正在完成状态说明任务完成
if (q != null)
q.thread = null; //销毁当前线程
return s; //返回状态
}
else if (s == COMPLETING) // cannot time out yet
Thread.yield(); //等于正在完成状态,调用方法等待
else if (q == null) //阻塞队列的判断等等
q = new WaitNode();
else if (!queued)
queued = UNSAFE.compareAndSwapObject(this, waitersOffset, q.next = waiters, q);
else if (timed) {
nanos = deadline - System.nanoTime();
if (nanos <= 0L) {
removeWaiter(q);
return state;
}
LockSupport.parkNanos(this, nanos);
}
else
LockSupport.park(this);
}
}
FutureTask线程的状态
我们上面一直再说各种状态的判断,其实这个状态的值就是在FutureTask类中设置的。
/**
* The run state of this task, initially NEW. The run state
* transitions to a terminal state only in methods set,
* setException, and cancel. During completion, state may take on
* transient values of COMPLETING (while outcome is being set) or
* INTERRUPTING (only while interrupting the runner to satisfy a
* cancel(true)). Transitions from these intermediate to final
* states use cheaper ordered/lazy writes because values are unique
* and cannot be further modified.
*
* Possible state transitions: 状态转换的四种情况:
* NEW -> COMPLETING -> NORMAL 创建->正在完成->正常结束
* NEW -> COMPLETING -> EXCEPTIONAL 创建->正在完成->异常
* NEW -> CANCELLED 创建->被取消
* NEW -> INTERRUPTING -> INTERRUPTED 创建->正在中断->完成中断
*/
private volatile int state;
private static final int NEW = 0;
private static final int COMPLETING = 1;
private static final int NORMAL = 2;
private static final int EXCEPTIONAL = 3;
private static final int CANCELLED = 4;
private static final int INTERRUPTING = 5;
private static final int INTERRUPTED = 6;
通过对各个状态的比较来确定如何执行线程的逻辑,之所以使用数字表示是因为状态变量加了volatile
关键字,这个关键字以后有机会再详细说,目前它的作用就是保证变量state
在多线程中的可见性。变量state
是为了表示当前线程的状态,而后面那些表示状态名字的变量则是为了比较或者更新state
表示的状态使用的。这些状态转换的四种情况也在注释里标明了。
总结
本篇就把有关Callable接口,Future接口和FutureTask类是如何使用的,以及结果集在底层是如何获取的,线程在FutureTask中的状态划分等等内容,从源码层面做了一个详细的分析。在本篇中挖了两个坑一个是volatile,另一个是线程池,这些内容后面都会做专门的讲解。关于线程的内容还有很多下一篇【Java 线程知识笔记 (三) Executor与ThreadPool 其一】就会说下Executor和线程池又是怎么用的。
附:实现 Runnable 接口和实现 Callable 接口的区别
- 语法上Runnable 是自从 java1.1 就有了,而 Callable 是 1.5 之后才加上去的。
- 实现 Callable 接口的任务线程能返回执行结果,而实现 Runnable 接口的任务线程不能返回结果。
- Callable 接口的 call()方法允许抛出异常,而 Runnable 接口的 run()方法的异常只能在内部消化,不能继续上抛。
- 加入线程池运行,Runnable 使用 ExecutorService 的 execute 方法,Callable 使用 submit 方法。
注:Callable 接口支持返回执行结果,此时需要调用 FutureTask.get()方法实现,此方法会阻塞主线程直到获取返回结果,当不调用此方法时,主线程不会阻塞。