1. 程式人生 > >理解高併發(15).Future、Callable實現原理及用法

理解高併發(15).Future、Callable實現原理及用法

概述 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); } }