ExecutorService

定義

DOC:

An Executor that provides methods to manage termination and methods that can produce a Future for tracking progress of one or more asynchronous tasks.

An ExecutorService can be shut down, which will cause it to reject new tasks. Two different methods are provided for shutting down an ExecutorService. The shutdown() method will allow previously submitted tasks to execute before terminating, while the shutdownNow() method prevents waiting tasks from starting and attempts to stop currently executing tasks. Upon termination, an executor has no tasks actively executing, no tasks awaiting execution, and no new tasks can be submitted. An unused ExecutorService should be shut down to allow reclamation of its resources.
Method submit extends base method execute(Runnable) by creating and returning a Future that can be used to cancel execution and/or wait for completion. Methods invokeAny and invokeAll perform the most commonly useful forms of bulk execution, executing a collection of tasks and then waiting for at least one, or all, to complete. (Class ExecutorCompletionService can be used to write customized variants of these methods.)

翻譯:

  1. 首先他是一個執(zhí)行器(Executor)匾七,增強(qiáng)版的執(zhí)行器:可以管理執(zhí)行器的關(guān)閉〗ぃ可以將異步任務(wù)包裝成Future任務(wù)(跟蹤任務(wù)的狀態(tài))
  1. 一個ExecutorService 可以被關(guān)閉昨忆,這樣新的任務(wù)來了將會拒絕新的任務(wù)。方法為:shutdown(新的任務(wù)不執(zhí)行杉允,老的任務(wù)將等待其執(zhí)行完成)邑贴,shutdownNow(新任務(wù)不執(zhí)行,老任務(wù)嘗試關(guān)閉)叔磷。
  2. 其中的 submit方法基于 execute方法拢驾。他將會生成一個Future任務(wù)(可以被cancel和等待執(zhí)行完成)

官方例子

網(wǎng)絡(luò)任務(wù)的多線程處理:

class NetworkService implements Runnable {
   private final ServerSocket serverSocket;
   private final ExecutorService pool;

   public NetworkService(int port, int poolSize)
       throws IOException {
     serverSocket = new ServerSocket(port);
     pool = Executors.newFixedThreadPool(poolSize);
   

   public void run() { // run the service
     try {
       for (;;) {
         pool.execute(new Handler(serverSocket.accept()));
       }
     } catch (IOException ex) {
       pool.shutdown();
     }
   }
 }
class Handler implements Runnable {
   private final Socket socket;
   Handler(Socket socket) { this.socket = socket; }
   public void run() {
     // read and service request on socket
   }
 }}

如下是關(guān)閉 ExecutorService的兩個步驟:

  1. 拒絕新來的任務(wù),等待老的任務(wù)去執(zhí)行完畢改基。
  2. 調(diào)用shutdownNow gg思密達(dá)
 void shutdownAndAwaitTermination(ExecutorService pool) {
   pool.shutdown(); // Disable new tasks from being submitted
   try {
     // Wait a while for existing tasks to terminate
     if (!pool.awaitTermination(60, TimeUnit.SECONDS)) {
       pool.shutdownNow(); // Cancel currently executing tasks
       
     // Wait a while for tasks to respond to being cancelled
     if (!pool.awaitTermination(60, TimeUnit.SECONDS))
           System.err.println("Pool did not terminate");
     
   } catch (InterruptedException ie) {
     // (Re-)Cancel if current thread also interrupted
     pool.shutdownNow();
     // Preserve interrupt status
     Thread.currentThread().interrupt();
   }
 }}

直接子類 AbstractExecutorService

提供newTaskFor()方法繁疤,將runable,callable包裝成RunnableFuture

結(jié)構(gòu):

由上圖知:AbstractExecutorService 是對 ExcutorService的默認(rèn)實現(xiàn)。

官方例子

 public class CustomThreadPoolExecutor extends ThreadPoolExecutor {
  // ThreadPoolExecutor 繼承自 ExecutorService

   static class CustomTask  implements RunnableFuture  {...

   protected   RunnableFuture  newTaskFor(Callable  c) {
       return new CustomTask (c);
   }
   protected   RunnableFuture  newTaskFor(Runnable r, V v) {
       return new CustomTask (r, v);
   }
   // ... add constructors, etc.
 }}

代碼實現(xiàn):

將runnable和callable包裝成RunnableFuture


最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末稠腊,一起剝皮案震驚了整個濱河市躁染,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌架忌,老刑警劉巖吞彤,帶你破解...
    沈念sama閱讀 216,591評論 6 501
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異鳖昌,居然都是意外死亡备畦,警方通過查閱死者的電腦和手機(jī)低飒,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,448評論 3 392
  • 文/潘曉璐 我一進(jìn)店門许昨,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人褥赊,你說我怎么就攤上這事糕档。” “怎么了拌喉?”我有些...
    開封第一講書人閱讀 162,823評論 0 353
  • 文/不壞的土叔 我叫張陵速那,是天一觀的道長。 經(jīng)常有香客問我尿背,道長端仰,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,204評論 1 292
  • 正文 為了忘掉前任田藐,我火速辦了婚禮荔烧,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘汽久。我一直安慰自己鹤竭,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,228評論 6 388
  • 文/花漫 我一把揭開白布景醇。 她就那樣靜靜地躺著臀稚,像睡著了一般。 火紅的嫁衣襯著肌膚如雪三痰。 梳的紋絲不亂的頭發(fā)上吧寺,一...
    開封第一講書人閱讀 51,190評論 1 299
  • 那天,我揣著相機(jī)與錄音散劫,去河邊找鬼稚机。 笑死,一個胖子當(dāng)著我的面吹牛抒钱,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 40,078評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼仗扬,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了蕾额?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 38,923評論 0 274
  • 序言:老撾萬榮一對情侶失蹤诅蝶,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后调炬,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體语盈,經(jīng)...
    沈念sama閱讀 45,334評論 1 310
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡刀荒,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,550評論 2 333
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了棘钞。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 39,727評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡宜猜,死狀恐怖泼返,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情姨拥,我是刑警寧澤绅喉,帶...
    沈念sama閱讀 35,428評論 5 343
  • 正文 年R本政府宣布,位于F島的核電站垫毙,受9級特大地震影響霹疫,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜综芥,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,022評論 3 326
  • 文/蒙蒙 一丽蝎、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧膀藐,春花似錦屠阻、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,672評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至虾啦,卻和暖如春麻诀,著一層夾襖步出監(jiān)牢的瞬間痕寓,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 32,826評論 1 269
  • 我被黑心中介騙來泰國打工蝇闭, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留呻率,地道東北人。 一個月前我還...
    沈念sama閱讀 47,734評論 2 368
  • 正文 我出身青樓呻引,卻偏偏與公主長得像礼仗,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子逻悠,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,619評論 2 354

推薦閱讀更多精彩內(nèi)容

  • 時間匆匆流過元践,我已經(jīng)畢業(yè)兩年了。突然發(fā)現(xiàn)奧運(yùn)冠軍比自己小了好幾歲童谒,自己的同齡人已經(jīng)達(dá)到了自己永遠(yuǎn)不可能的高度单旁。 也...
    xiaojinwu閱讀 207評論 0 0
  • 陳女士和她的前夫結(jié)婚才半年就離婚了撵渡。她告訴我一些關(guān)于她和她前夫的事。在他們談戀愛的那三年里死嗦,她前夫每天都很勤快趋距,把...
    康蘭居閱讀 3,831評論 9 57
  • 配合ios完成分享頁的對接,以及頁面的測試修改越除。和方碩配合實現(xiàn)書院流程节腐。 期間因為appid的事出過岔子,以后對待...
    LiLiLiH閱讀 157評論 0 0
  • 小時候畫在手上的表沒有動摘盆,卻帶走了我們最好的時光翼雀。 不要輕易把傷口揭開給別人看,因為別人看的是熱鬧孩擂,而痛的卻是...
    雪茜閱讀 423評論 0 0