理解java多線程中ExecutorService使用_java

來源:互聯網
上載者:User

java.util.concurrent包裡提供了關於多線程操作的類,平常用的比較多的是ExecutorService及其實作類別(如ThreadPoolExecutor等),Executor,Executors,Future,Callable等

1. ExecutorService(繼承自Executor)介面:提供了一些非同步多線程操作方法,如execute(), submit(), shutdown(), shutdownNow()等

2. Executor介面:執行提交的任務(線程),只有一個方法 execute(Runnable a)

2. Executors類: 提供了一些Factory 方法和一些公用方法來操作Executor子類和ThreadFactory等,如newXXX(),xxxThreadFactory()等

3. Futrue介面:代表了線程執行結果,提供了擷取線程執行結果和取消線程的方法,如get(),cancle()等

4. Callable介面:JDK1.5提供的有傳回值的線程執行新介面

對ExecutorService和Future的理解做簡單記錄

代碼:

public class Main {  private static int count = 0;  public static void main(String[] args){    List<Future> resultList = new LinkedList<>();    /**     * Executors.newCachedThreadPool() 建立一個線程緩衝池,若60s中線程沒有被使用,則會停止線程並從緩衝池中移除     * Executors.newScheduledThreadPool() 建立一個固定容量的線程池,裡邊的線程按照設定的調度時間執行     * Executors.newFixedThreadPool()  擁有固定容量的線程緩衝池     * Executors.newSingleThreadExecutor() 容量為一的線程緩衝池,只會有一個線程     */    ExecutorService executorService = Executors.newCachedThreadPool();    for(int i=0; i<10; i++){      Future future = executorService.submit(new Callable<String>() {        @Override        public String call() {          try {            System.out.println(Thread.currentThread().getName());            Thread.sleep(5000);          } catch (InterruptedException e) {            e.printStackTrace();          }          int count = Main.count;          System.out.println(Thread.currentThread().getName() + "..start Main count:..." + count);          Main.count = ++count;          System.out.println(Thread.currentThread().getName() + "..end Main count:..." + Main.count);          return Thread.currentThread().getName();        }      });      resultList.add(future);    }    executorService.shutdown();    for(Future future: resultList){      try {        System.out.println(future.get() + "..is over...");      } catch (InterruptedException e) {        e.printStackTrace();      } catch (ExecutionException e) {        e.printStackTrace();      }    }    System.out.println("main thread end...");  }}

輸出:

pool-1-thread-1pool-1-thread-2pool-1-thread-3pool-1-thread-4pool-1-thread-5pool-1-thread-6pool-1-thread-7pool-1-thread-8pool-1-thread-9pool-1-thread-10pool-1-thread-1..start Main count:...0pool-1-thread-2..start Main count:...0pool-1-thread-3..start Main count:...1pool-1-thread-2..end Main count:...1pool-1-thread-1..end Main count:...1pool-1-thread-3..end Main count:...2pool-1-thread-1..is over...pool-1-thread-2..is over...pool-1-thread-4..start Main count:...2pool-1-thread-3..is over...pool-1-thread-4..end Main count:...3pool-1-thread-4..is over...pool-1-thread-5..start Main count:...3pool-1-thread-5..end Main count:...4pool-1-thread-5..is over...pool-1-thread-6..start Main count:...4pool-1-thread-6..end Main count:...5pool-1-thread-6..is over...pool-1-thread-7..start Main count:...5pool-1-thread-7..end Main count:...6pool-1-thread-7..is over...pool-1-thread-8..start Main count:...6pool-1-thread-8..end Main count:...7pool-1-thread-8..is over...pool-1-thread-9..start Main count:...7pool-1-thread-9..end Main count:...8pool-1-thread-9..is over...pool-1-thread-10..start Main count:...8pool-1-thread-10..end Main count:...9pool-1-thread-10..is over...main thread end... //主線程在所有線程執行完成後結束

控制台在等待5秒後列印出上邊的輸出結果,原因是所有的線程啟動的時候是一個並行作業,都會去等待5秒,所以整體看來只等了5秒,這是一個並行作業

總結:

1. ExecutorService提供的execute()方法和submit()方法的區別:

  a. execute()方法只接受Runnable類型的執行個體,所以不能拿到傳回值,也不能動態擷取線程執行的情況

  b. submit()方法接受Runnable和Callable執行個體,會返回Future執行個體,Future執行個體的get()方法可以擷取線程執行傳回值,並能拋出線程執行異常。所以如果要擷取線程執行返回的結果,並能處理線程執行時可能出現的異常,或者想中途取消線程執行時可以使用submit()方法

2. 通過輸出可以看到main方法(主線程)在所有線程執行完成後結束,原因:

  a. 通過submit()方法擷取Future執行個體,並通過Future執行個體的get()方法擷取線程返回結果,而Future執行個體的get()方法會等待線程執行完畢才會返回,所以main方法會等待所有子線程結束才會結束

  b. 若去掉上邊紅色標註的for迴圈,則main方法(主線程)會提前結束,而不會等待所有子線程結束

補充:

1. 多個線程並發執行時,若其中某一個線程出現了異常並且沒有被處理,則該線程會自動停止執行,但其他線程還是會正常執行,這就是為什麼tomcat請求出現異常時,tomcat還可以繼續提供服務的原因。

2. tomcat提供了線程池和等待池,每一個請求過來都會重新啟動一個新的線程處理該請求,若線程池中線程用完,再來請求的時候就會放到等待池中等待,當其中有線程釋放回線程池中時,就會為等待池中的請求分配線程處理請求。

以上就是本文的全部內容,希望對大家的學習有所協助,也希望大家多多支援雲棲社區。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.