日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

多线程创建方式 线程池、Future和CompletableFuture

發布時間:2023/12/10 编程问答 26 豆豆
生活随笔 收集整理的這篇文章主要介紹了 多线程创建方式 线程池、Future和CompletableFuture 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

大家好,我是烤鴨:

? ? ?今天說一下 多線程的幾種創建方式及使用。

1. Thread 和 Runnable


?? ?繼承 Thread 類 和實現 Runnable 接口。
?? ?這種就不舉例子了。

2.線程池


? 現在主要有5種線程池。

//緩存線程池ExecutorService cachedThreadPool = Executors.newCachedThreadPool();?//固定大小線程池ExecutorService fixedThreadPool = Executors.newFixedThreadPool(10);//單線程執行ExecutorService singleThreadPool = Executors.newSingleThreadExecutor();//定時或延遲執行ExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(10);//竊取線程池ExecutorService workStealingPool = Executors.newWorkStealingPool();

其中 newWorkStealingPool 是jdk 1.8以后新出的,為了防止線程池啟用過多,導致cpu占用過多導致的項目宕機。適用于執行多任務,且每個任務耗時時間較短。
? 其余4種方式都有可能會出現占用cpu過高導致的項目宕機的情況。
? 以 4核 16G的機器為例, Executors.newFixedThreadPool(10) 這種方式創建的線程池大小為10
? Executors.newWorkStealingPool() 創建線程池大小為4。一般來說,和核數相等
? 即便不使用這種方式,也建議不要超過 核數 * 2。(具體看需求)


3. Future和CompletableFuture


Future 是 jdk1.5 以后出現的,用于異步多線程。
例子:

// 創建Future集合,用于存放完成的Future List<Future<Long>> futureList = new ArrayList(); //多線程執行任務 for (int i = 0; i < 100; i++) {Future<Long> testFuture= workStealingPool.submit(new Callable<Long>() {@Overridepublic Long call() {//模擬執行耗時任務System.out.println("task 1 doing...");try {Thread.sleep(1000);} catch (Exception e) {e.printStackTrace();}return 0L;}});futureList.add(testFuture); } //遍歷list,獲取線程結果 for (Future<Long> taskResponseFuture: futureList) {if(taskResponseFuture.get().equals(0L)){//當前future執行完畢} }

這里注意一下,Future.get()是阻塞方法。如果需要多線程執行操作,在最后的時候執行get()方法。
類似上邊的例子,可以把 多個 Future 放到list中,再循環get。

CompletableFuture 是 Future的實現類,關于異步多線程提供了更多的api,下面介紹幾種常用的。


supplyAsync 異步執行,有返回值

CompletableFuture<Integer> completableFuture1 = CompletableFuture.supplyAsync(() -> {//模擬執行耗時任務System.out.println("task 1 doing...");try {Thread.sleep(1000);} catch (Exception e) {e.printStackTrace();}//返回結果return 0; });

thenAccept 接收上一階段的輸出作為本階段的輸入。多線程(單個線程)的順序執行。

completableFuture1.thenApply(new Function<Integer, Object>() {@Overridepublic Object apply(Integer integer) {//模擬執行耗時任務System.out.println("task thenApply doing...");try {Thread.sleep(1000);} catch (Exception e) {e.printStackTrace();}return 0;} });

whenComplete 異步監聽結果

completableFuture1.whenComplete(new BiConsumer<Integer,Throwable>() {@Overridepublic void accept(Integer o, Throwable o2) {if(o == 0L){System.out.println("task complete...");}else{throw new RuntimeException();}} });

?

總結

以上是生活随笔為你收集整理的多线程创建方式 线程池、Future和CompletableFuture的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。