理解高并发(15).Future、Callable实现原理及用法

来源:互联网 发布:小米3支持电信4g网络吗 编辑:程序博客网 时间:2024/05/16 16:19
概述
jdk1.5推出的,使用它能带来2个方便:
  • 能够获得到线程执行后返回的结果
  • 线程异常有效捕获

简单例子
输出结果:result=hello
public class ThreadLocalTest {
@SuppressWarnings("unchecked")
public static void main(String[] args) {
ExecutorService executor = Executors.newCachedThreadPool();
Callable able = new WorkThread();
Future<String> future = executor.submit(able);
try {
String s = future.get();
System.out.println("reuslt=" + s);
} catch (Exception e) {
e.printStackTrace();
}
executor.shutdown();
}
static class WorkThread implements Callable<String> {
public String call() throws Exception {
return "hello";
}
}
}

原理分析
需要弄清楚2个问题:
1. 线程如何执行到call方法?
整个过程的核心在构建RunnableFuture, 当触发submit时,会去构建一个RunnableFuture对象,该对象实现了Runnable和Future接口,所以具体线程的特性和Future的特性。
构建完RunnableFuture对象后,交由线程池去处理,线程池会去触发调用RunnableFuture中的run, 而在run方法中又调用了call方法。
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);
}
}
2. 如何获得到返回值?
构造完RunnableFuture对象后, 会将该对象的句柄返回给调用者线程。 调用者线程如果调用了RunnableFuture.get(), 当前线程会被阻塞,会采用cas实现机制循环探测线程是否执行完毕,执行完毕则立马回。
里面运用了LockSupport.park /LockSupport.unpark 进行线程通信, get值时如果任务没有执行完,LockSupport.park阻塞线程; put值时,lockSupport.unpark唤醒阻塞;
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);
}
}

原创粉丝点击