從頭認識java-17.7 執行器(Executor)

來源:互聯網
上載者:User

從頭認識java-17.7 執行器(Executor)

這一章節我們來討論一下Executor的線程池。

1.什麼是線程池?(下面的解釋來自http://baike.haosou.com/doc/2511076-2653416.html)

線程池是一種多執行緒形式,處理過程中將任務添加到隊列,然後在建立線程後自動啟動這些任務。線程池線程都是後台線程。每個線程都使用預設的堆棧大小,以預設的優先順序運行,並處於多執行緒 Apartment中。如果某個線程在Managed 程式碼中空閑(如正在等待某個事件),則線程池將插入另一個輔助線程來使所有處理器保持繁忙。如果所有線程池線程都始終保持繁忙,但隊列中包含掛起的工作,則線程池將在一段時間後建立另一個輔助線程但線程的數目永遠不會超過最大值。超過最大值的線程可以排隊,但他們要等到其他線程完成後才啟動。

2.作用:

(1)集中管理線程

(2)提高線程的利用率,因為應用程式都會啟動多個線程,而這些線程可能在大部分的時間裡面都屬於休眠或者等待狀態,我們就需要把它們利用起來。

 

3.例子:

(1)系統自動管理線程數量

 

package com.ray.ch17;import java.util.Random;import java.util.concurrent.Callable;import java.util.concurrent.ExecutionException;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;import java.util.concurrent.Future;public class Test {public static void main(String[] args) throws InterruptedException,ExecutionException {ExecutorService executors = Executors.newCachedThreadPool();Callable callable = new MyCall();Future future = executors.submit(callable);System.out.println(future.get());executors.shutdown();}}class MyCall implements Callable {@Overridepublic Integer call() throws Exception {System.out.println("doing something...");Thread.sleep(1000);return new Random().nextInt(50);}}
輸出:

doing something...
17

(2)手動設定線程數量

package com.ray.ch17;import java.util.Random;import java.util.concurrent.Callable;import java.util.concurrent.ExecutionException;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;import java.util.concurrent.Future;public class Test {public static void main(String[] args) throws InterruptedException,ExecutionException {ExecutorService executors = Executors.newFixedThreadPool(2);Callable callable = new MyCall();Future future = executors.submit(callable);System.out.println(future.get());executors.shutdown();}}class MyCall implements Callable {@Overridepublic Integer call() throws Exception {System.out.println("doing something...");Thread.sleep(1000);return new Random().nextInt(50);}}

輸出:

doing something...
17

4.注意點:

(1)建立線程池的時候我們可以根據實際情況來決定線程的數量或者是由系統決定

(2)使用submit方法提交Runnable或者Callable任務

(3)如果想取消任務或者提交了Callable任務,需要儲存Future返回的對象

(4)最後記得加上shundown方法,關閉線程池。

總結:這一章節主要介紹了Executor的線程池。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.