並行執行器
阿新 • • 發佈:2018-11-28
工作中出現某些程式碼需要並行執行以提高程式運算速度的情況,所以寫了一個小工具。
public class Main { public static void main(String[] args) { // 你可以通過註釋下面的部分程式碼來探索它的功能, // 一些重要的說明請到程式碼中尋找,註釋寫的很清楚 new ParallelInvoker().call(invoker -> { // call方法啟動執行器 System.out.println("1"); try { Thread.sleep(5000); } catch (InterruptedException e) { e.printStackTrace(); } invoker.reject(new Exception("e1")); System.out.println("2"); }).and(invoker -> { System.out.println("3"); invoker.reject(new Exception("e2")); System.out.println("4"); }).then(invoker -> { // then將前後斷開,只有前面的回撥全部執行完,且沒有發生catched(沒有呼叫reject),才會執行then後的函式,此處呼叫了reject,所以"then 開始"不會被列印 System.out.println("then 開始"); invoker.reject(new Exception()); try { Thread.sleep(5000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("then 結束"); }).continued().catched(e -> { // continued標識可讓主執行緒不等待被標記點的執行 System.out.println(e.getMessage()); }).start(); System.out.println("main continue"); } }
結果:
1
3
e2
4
main continue
2
專案在GitHub上,點這裡