Runnable和Callable的区别
了解一下
在java中线程类是java.lang.Thread
,看源码可知线程类是实现了java.lang.Runnable
接口的。我们如果想运行一个线程,可以新建一个java.lang.Thread
并重写run()
方法去执行自己的任务,当然也可以向java.lang.Thread
对象中填入一个实现了java.lang.Runnable
接口的类。
那java.util.concurrent.Callable
接口是什么?定义了返回结果的任务接口,和java.lang.Runnable
相似,但是其使用还是要依赖java.lang.Runnable
,为什么这么说呢,请往下看。
Callable的使用
在java中,Callable的最先是在线程池中使用的。
public <T> Future<T> submit(Callable<T> task) {
if (task == null) throw new NullPointerException();
RunnableFuture<T> ftask = newTaskFor(task); //封装Callable为FutureTask
execute(ftask); //运行FutureTask
return ftask; //返回FutureTask
}
FutureTask
- Future接口
取消任务
获取任务结果(检查计算是否为完成,等待其完成再返回结果,一旦完成,无法取消) - RunnableFuture继承了Runnable和Future
- FutureTask是RunnableFuture的实现类,也就是实现了Runnable和Future的功能
FutureTask功能: 启动,取消,查询是否完成检索计算结果,如果计算未完成,方法将阻塞,一旦计算完成,无法重新计算或取消除非调用
runAndReset()
状态
状态变化:
方法
- 构造方法:
public FutureTask(Callable<V> callable) {
if (callable == null)
throw new NullPointerException();
this.callable = callable;
this.state = NEW; // ensure visibility of callable
}
public FutureTask(Runnable runnable, V result) {
this.callable = Executors.callable(runnable, result); //通过Runnable封装为RunnableAdapter,而RunnableAdapter实现了Callable
this.state = NEW;
}
run
方法
public void run() {
if (state != NEW ||
!UNSAFE.compareAndSwapObject(this, runnerOffset,
null, Thread.currentThread()))
return;
try {
Callable<V> c = callable;
if (c != null && state == NEW) {
V result;
boolean ran;
try {
result = c.call(); //获取call的结果
ran = true;
} catch (Throwable ex) {
result = null;
ran = false;
setException(ex);
}
if (ran)
set(result);//将call的结果存储起来
}
} 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);
}
}
get
方法
public V get() throws InterruptedException, ExecutionException {
int s = state;
if (s <= COMPLETING)
s = awaitDone(false, 0L); //如果没有完成,等待结果返回
return report(s);
}
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 (;;) {
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);
}
}