【多線程】八、異步計算結果獲取

相關文章:
【多線程】一、線程狀態切換
【多線程】二、線程優先級&守護線程
【多線程】三、線程訪問變量
【多線程】四、線程異常抓捕
【多線程】五、線程池
【多線程】六、鎖與同步
【多線程】七、阻塞隊列
【多線程】八、異步計算結果獲取
【多線程】九、Android異步任務

競爭分量
爲解決大量線程競爭問題, 子線程基於分量計算(分量在單線程模型上保證原子性),計算完畢後合併分量取結果;

// Adder: LongAdder, DoubleAdder
// Accumulator: LongAccumulator, DoubleAccumulator

// 初始化
LongAdder adder = new LongAdder();
LongAccumulator accumulator = new LongAccumulator(Math::max, -1);

// 分量計算
adder.add(x); // adder.increment();
accumulator.accumulate(x);

// 獲取總量
adder.sum();
accumulator.get();

延時返回

相關 說明
Callable<T> 異步任務計算
Runnable相比有返回值,可拋異常
Future<T> 異步任務結果獲取
T get([long timeout, TimeUnit unit]):阻塞,直到計算完成返回;
boolean cancel(boolean mayInterrupt):取消計算
boolean isCancelled():是否在完成前就被取消了
boolean isDone():是否任務結束(自然結束或異常死亡)
FutureTask Callable對象轉換成RunnableFuture
futureTask = new FutureTask<>(callable);
new Thread(futureTask).start();
result = futureTask.get();

異步閂

// 初始化,指定開閂任務數
CountDownLatch latch = new CountDownLatch(4);

// 指派子任務完畢,關閂; 線程阻塞於此
latch.await();

// 子任務執行完畢,通知開閂
latch.countDown(); 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章