FutureTask的使用示例
static class MyCallable implements Callable {
@Override
public Object call() throws Exception {
return 10086;
}
}
public static void threadExamples() {
MyCallable myCallable = new MyCallable();
FutureTask<Integer> ft = new FutureTask<>(myCallable);
new Thread(ft).start();
try {
System.out.println(ft.get());
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
console输出: 10086
以下部分为FutureTask源码分析
Callable接口
package java.util.concurrent;
/**@param <V> the result type of method
*/
@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;
}
thread 的构造函数
public Thread(Runnable target) {
init(ThreadGroup:null, target, "Thread Name", stackSize:0);
}
从
的构造方法中我们可以看出,
需要一个
参数,而
是一个
的实现类吗?我们先看一下下面这段代码和
类图
public class FutureTask<V> implements RunnableFuture<V>
public interface RunnableFuture<V> extends Runnable, Future<V>

从代码源码中我们可以看出
实现了
接口,而
接口继承自
接口和
接口
Thread源码部分——run方法
@Override
public void run() {
if (target != null) {
target.run();
}
}
从
的
方法可以得知,
方法内部其实就是调用了target的
方法 ,在第三种实现方式里
FutureTask<V>的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();
ran = true;
} catch (Throwable ex) {
result = null;
ran = false;
setException(ex);
}
if (ran)
set(result);
}
} 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);
}
}
在
的
方法里就是回调了
的
方法,我们知道
其实是一个接口,所以最终还是在他的实现类里实现,而我们自己定义了一个
类实现了
接口,在call里我们可以写上自己的一系列操作,然后返回一个对象给
的
方法里的
,然后调用
方法,将
对象设置给
![]()
FutureTask的set方法和get方法
protected void set(V v) {
if (UNSAFE.compareAndSwapInt(this, stateOffset, NEW, COMPLETING)) {
outcome = v;
UNSAFE.putOrderedInt(this, stateOffset, NORMAL); // final state
finishCompletion();
}
}
public V get() throws InterruptedException, ExecutionException {
int s = state;
if (s <= COMPLETING)
s = awaitDone(false, 0L);
return report(s);
}
public V get(long timeout, TimeUnit unit)
throws InterruptedException, ExecutionException, TimeoutException {
if (unit == null)
throw new NullPointerException();
int s = state;
if (s <= COMPLETING &&
(s = awaitDone(true, unit.toNanos(timeout))) <= COMPLETING)
throw new TimeoutException();
return report(s);
}
FutureTask的report方法
@SuppressWarnings("unchecked")
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);
}
从上面的代码可以看出,我们调用
的对象的
方法,
方法会去调用
方法返回
,而
方法不是立刻返回的,他会等待我们的
函数执行完成才会返回,调用
的线程才会继续执行,因为
方法里有一个阻塞式的方法。他会判断
函数的执行是否结束,没有结束就会调用
方法,
方法会根据是否有时间限制,如果有,在时钟到达前都会阻塞调用
的线程,如果始终已经到达,但是
方法还是没有执行完,那么就抛出一个
,如果
不带时间限制,那么他就会调用
方法阻塞调用
的线程
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);
}
}
LockSupport的park方法
public static void park(Object blocker) {
Thread t = Thread.currentThread();
setBlocker(t, blocker);
UNSAFE.park(false, 0L);
setBlocker(t, null);
}
网友评论