多线程创建方式 线程池、Future和CompletableFuture
大家好,我是烤鴨:
? ? ?今天說一下 多線程的幾種創建方式及使用。
1. Thread 和 Runnable
?? ?繼承 Thread 類 和實現 Runnable 接口。
?? ?這種就不舉例子了。
2.線程池
? 現在主要有5種線程池。
其中 newWorkStealingPool 是jdk 1.8以后新出的,為了防止線程池啟用過多,導致cpu占用過多導致的項目宕機。適用于執行多任務,且每個任務耗時時間較短。
? 其余4種方式都有可能會出現占用cpu過高導致的項目宕機的情況。
? 以 4核 16G的機器為例, Executors.newFixedThreadPool(10) 這種方式創建的線程池大小為10。
? Executors.newWorkStealingPool() 創建線程池大小為4。一般來說,和核數相等。
? 即便不使用這種方式,也建議不要超過 核數 * 2。(具體看需求)
3. Future和CompletableFuture
Future 是 jdk1.5 以后出現的,用于異步多線程。
例子:
這里注意一下,Future.get()是阻塞方法。如果需要多線程執行操作,在最后的時候執行get()方法。
類似上邊的例子,可以把 多個 Future 放到list中,再循環get。
CompletableFuture 是 Future的實現類,關于異步多線程提供了更多的api,下面介紹幾種常用的。
supplyAsync 異步執行,有返回值
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的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【Xamarin挖墙脚系列:最重要的布局
- 下一篇: Js基础知识梳理系列