原文链接
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| public class FutureAndCallableExample { public static void main(String[] args) throws InterruptedException, ExecutionException { ExecutorService executorService = Executors.newSingleThreadExecutor();
Callable<String> callable = () -> { Thread.sleep(2000); return "Hello, Martian!"; };
Future<String> future = executorService.submit(callable);
String result = future.get();
System.out.println(result);
executorService.shutdown(); } }
|
关于futureTask的核心代码
1 2 3 4
| Callable<V> c = callable; V result; result = c.call(); set(result);
|
在executor service里面submit一个任务的全流程:
- 我们通过Executors得到一个ExecutorService
- 我们创建一个Callable的任务
- 我们把callable的任务submit进ExecutorService
- ExecutorService把我们的callable任务封装成FutureTask
- ExecutorService帮我们管理运行task所需要的thread,并把thread和task都交给worker去执行。
- worker负责在thread里面执行task。
- task的类型是FutureTask,在内部执行我们的callable task,并把结果放在内部的outcome变量里。
future.get
1 2 3 4 5 6
| public V get() throws InterruptedException, ExecutionException { int s = state; if (s <= COMPLETING) s = awaitDone(false, 0L); return report(s); }
|
关于awaitDone方法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
| 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) 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); } }
|