java多線程-05-Excutor家族

[TOC]

聲明

該系列文章只是記錄本人回顧java多線程編程時(shí)候記錄的筆記。文中所用語言并非嚴(yán)謹(jǐn)?shù)膶I(yè)術(shù)語(太嚴(yán)謹(jǐn)?shù)男g(shù)語其實(shí)本人也不會(huì)……)。難免有理解偏差的地方,歡迎指正。
另外,大神請繞路。不喜勿噴。
畢竟好記性不如爛筆頭嘛,而且許多東西只要不是你經(jīng)常用的最終都會(huì)一丟丟一丟丟地給忘記。

1 Excutor家族概覽

上一篇 http://blog.csdn.net/hylexus/article/details/53456463 中介紹了java線程池的相關(guān)概念和基本用法。

然而在平時(shí)真正使用的時(shí)候往往不是自己手動(dòng)創(chuàng)建線程池的。而是通過本節(jié)要介紹的ExcutorExcutorService來使用的。

以下是Excutor家族的主要成員

ExcutorService家族

2 成員介紹

2.1 Executors

Executors是一個(gè)專門為Executor、ExecutorService、ScheduledExecutorServiceThreadFactory、Callable等設(shè)計(jì)的工廠類。

2.2 ThreadPoolExecutor

ThreadPoolExecutor就是 上一篇文章 介紹的線程池。他是整個(gè)線程池的核心組件。

然而,在多數(shù)情況下,ThreadPoolExecutor的實(shí)例的創(chuàng)建并不是我們自己new的。
而是通過java.util.concurrent.Executors這個(gè)工廠類來創(chuàng)建的。Executors提供方法以快捷的創(chuàng)建三種常用的 ThreadPoolExecutor

  • 固定大小的線程池
public static ExecutorService newFixedThreadPool(int nThreads){}
public static ExecutorService newFixedThreadPool(
    int nThreads, ThreadFactory threadFactory){
}
  • 單個(gè)線程的線程池
public static ExecutorService newSingleThreadExecutor(){}
public static ExecutorService newSingleThreadExecutor(
    ThreadFactory threadFactory){
}
  • 按需創(chuàng)建新線程的線程池

maximumPoolSize為Integer.MAX_VALUE,隊(duì)列類型為 SynchronousQueue.

public static ExecutorService newCachedThreadPool(){}
public static ExecutorService newCachedThreadPool(
    ThreadFactory threadFactory){
}

2.3 ScheduledThreadPoolExecutor

簡單理解就是可調(diào)度版的ThreadPoolExecutor。一般是用來執(zhí)行周期性的可調(diào)度的任務(wù)的。

Executors提供方法以快捷的創(chuàng)建 ScheduledThreadPoolExecutor

public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize){}
public static ScheduledExecutorService newScheduledThreadPool(
            int corePoolSize, ThreadFactory threadFactory) {
}

2.4 Runnable、Callable

這兩個(gè)接口表示可以被ScheduledThreadPoolExecutorThreadPoolExecutor執(zhí)行的任務(wù)的抽象。

Excutors工廠中提供了將Runnable包裝為Callable的方法:

public static Callable<Object> callable(Runnable task){}
public static <T> Callable<T> callable(Runnable task, T result) {}

2.5 Future、FutureTask

Future表示異步執(zhí)行的任務(wù)的返回結(jié)果。FutureTask是Future接口的間接實(shí)現(xiàn)類。

其實(shí)FutureTask不僅實(shí)現(xiàn)了Future接口,同時(shí)還實(shí)現(xiàn)了Runnable接口。

FutureTask的狀態(tài):

  • 未啟動(dòng):剛剛被創(chuàng)建,尚未調(diào)動(dòng)run()方法的狀態(tài)
  • 已啟動(dòng):調(diào)用了run()方法
  • 已完成:run方法執(zhí)行完畢

FutureTask類的常用方法:

  • get() : Waits if necessary for the computation to complete, and then retrieves its result.
    • 在未啟動(dòng)狀態(tài)調(diào)用get()==>阻塞
    • 在已啟動(dòng)狀態(tài)調(diào)用get()==>阻塞
    • 在已完成狀態(tài)調(diào)用get()==>返回執(zhí)行結(jié)果,或者拋出異常
  • cancel():取消執(zhí)行
    • 在未啟動(dòng)狀態(tài)調(diào)用cancel(),將導(dǎo)致該任務(wù)永遠(yuǎn)不會(huì)被執(zhí)行。
    • 在已啟動(dòng)狀態(tài)調(diào)用cancel(),將會(huì)使用中斷該任務(wù)線程的方式來嘗試取消任務(wù)的執(zhí)行。
    • 在調(diào)用時(shí)如果該任務(wù)已經(jīng)被終止、或已經(jīng)完成或者由于一些原因無法終止該方法都將返回false.

2.6 Executor、ExecutorService

java.util.concurrent.Executor是一個(gè)可以執(zhí)行提交給他的任務(wù)的對(duì)象的抽象接口。只包含一個(gè)方法:

void execute(Runnable command);

java.util.concurrent.ExecutorServiceExecutor的子接口,提供了更加豐富的接口方法。

3 簡單示例

ExecutorService service = Executors.newFixedThreadPool(12);
Future<List<String>> future = service.submit(new Callable<List<String>>() {
    @Override
    public List<String> call() throws Exception {
        // 模擬查詢耗時(shí)3秒
        Thread.sleep(3000);
        return Arrays.asList("tom", "cat", "apache", "Spark", "Scala");
    }
});

try {
    List<String> list = future.get();
    list.forEach(System.out::println);
} catch (InterruptedException e) {
    e.printStackTrace();
} catch (ExecutionException e) {
    e.printStackTrace();
} finally {
    service.shutdown();
}

參考資料

  • 《java并發(fā)編程的藝術(shù)》
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • Java-Review-Note——4.多線程 標(biāo)簽: JavaStudy PS:本來是分開三篇的,后來想想還是整...
    coder_pig閱讀 1,772評(píng)論 2 17
  • 下面是我自己收集整理的Java線程相關(guān)的面試題,可以用它來好好準(zhǔn)備面試。 參考文檔:-《Java核心技術(shù) 卷一》-...
    阿呆變Geek閱讀 15,142評(píng)論 14 507
  • layout: posttitle: 《Java并發(fā)編程的藝術(shù)》筆記categories: Javaexcerpt...
    xiaogmail閱讀 6,022評(píng)論 1 19
  • 前言:線程是稀缺資源,如果被無限制的創(chuàng)建,不僅會(huì)消耗系統(tǒng)資源,還會(huì)降低系統(tǒng)的穩(wěn)定性,合理的使用線程池對(duì)線程進(jìn)行統(tǒng)一...
    SDY_0656閱讀 854評(píng)論 0 1
  • 昨夜放歌矣,無眠到子深。 為師二十載,難說愛與恨。 年少輕狂時(shí),豪擲五千金。 偏愛上層樓,曾經(jīng)入高門。 飄蓬無根須...
    梅心梅飛閱讀 339評(píng)論 6 9

友情鏈接更多精彩內(nèi)容