JDK多任務執行架構(Executor架構),jdkexecutor

來源:互聯網
上載者:User

JDK多任務執行架構(Executor架構),jdkexecutor
Executor的常用方法

為了更好的控制多線程,JDK提供了一套線程架構Executor,協助開發人員有效地進行線程式控制制。它們都在java.util.concurrent包中,是JDK開發包的核心。其中有一個重要的類:Executors,他扮演這線程工廠的角色,我們通過Executors可以建立特定功能的線程池。

查看它們的源碼:

    public static ExecutorService newFixedThreadPool(int nThreads) {        return new ThreadPoolExecutor(nThreads, nThreads,                                      0L, TimeUnit.MILLISECONDS,                                      new LinkedBlockingQueue<Runnable>());    }    public static ExecutorService newSingleThreadExecutor() {        return new FinalizableDelegatedExecutorService            (new ThreadPoolExecutor(1, 1,                                    0L, TimeUnit.MILLISECONDS,                                    new LinkedBlockingQueue<Runnable>()));    }     public static ExecutorService newCachedThreadPool() {        return new ThreadPoolExecutor(0, Integer.MAX_VALUE,                                      60L, TimeUnit.SECONDS,                                      new SynchronousQueue<Runnable>());    }    public static ScheduledExecutorService newScheduledThreadPool(            int corePoolSize, ThreadFactory threadFactory) {        return new ScheduledThreadPoolExecutor(corePoolSize, threadFactory);    }    public ScheduledThreadPoolExecutor(int corePoolSize,                                       ThreadFactory threadFactory) {        //這裡super是ThreadPoolExecutor類        super(corePoolSize, Integer.MAX_VALUE, 0, NANOSECONDS,              new DelayedWorkQueue(), threadFactory);    }    
View Code

從源碼看以看出它們都是由ThreadPoolExecutor構造出來的。

ThreadPoolExecutor構造方法概述

ThreadPoolExecutor(

  int corePoolSize,//核心線程數,線程池剛初始化的時候執行個體化線程個數

  int maximumPoolSize,//最大線程數

  long keepLongTime,//空閑時間,過時回收

  TimeUnit unit,//時間單位

  BlockingQueue<Runable> worker,//線程暫緩處

  ThreadFactory threadFactory,

  RejectExecuteHandle handle//拒絕執行的方法

)

所以上面幾個方法主要是根據不同的參數來執行不同的行為。其中newScheduleThreadPool方法稍複雜一點,它的方法值是ScheduledExecutorService。

ScheduledExecutorService主要有兩個方法scheduleWithFixedDelay,scheduleAtFixedRate

1、scheduleAtFixedRate 方法,以固定的頻率來執行某項計劃(任務),即固定的頻率來執行某項計劃,它不受計劃執行時間的影響。到時間就執行。 它不受計劃執行時間的影響。
2、scheduleWithFixedDealy,相對固定的延遲後,執行某項計劃(任務), 即無論某個任務執行多長時間,等執行完了,我再延遲指定的時間去執行。它受計劃執行時間的影響。

class Temp extends Thread {    public void run() {        try {            System.out.println( new Date().toString() + "..run start");            Thread.sleep(3000);            System.out.println( new Date().toString() + "...run end");        } catch (InterruptedException e) {            // TODO Auto-generated catch block            e.printStackTrace();        }    }}public class ScheduledJob {        public static void main(String args[]) throws Exception {            Temp command = new Temp();        ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);        System.out.println(new Date().toString() + "...start");        //scheduler.scheduleWithFixedDelay(command, 5, 2, TimeUnit.SECONDS);        scheduler.scheduleAtFixedRate(command, 5, 2, TimeUnit.SECONDS);    }}
View Code

scheduleAtFixedRate 的執行結果:run方法延遲了5秒執行,run方法執行了3秒,已經超過了我們指定的間隔2秒,所以它在第一個run方法執行完後,立即執行了第二個run方法

Tue Feb 06 15:48:01 CST 2018...startTue Feb 06 15:48:06 CST 2018..run startTue Feb 06 15:48:09 CST 2018...run endTue Feb 06 15:48:09 CST 2018..run startTue Feb 06 15:48:12 CST 2018...run endTue Feb 06 15:48:12 CST 2018..run start

scheduleWithFixedDealy的執行結果:run方法延遲了5秒執行,run方法執行了3秒,已經超過了我們指定的間隔2秒,但是它還是等了2秒後,再執行了第二個run方法

Tue Feb 06 15:53:04 CST 2018...startTue Feb 06 15:53:10 CST 2018..run startTue Feb 06 15:53:13 CST 2018...run endTue Feb 06 15:53:15 CST 2018..run startTue Feb 06 15:53:18 CST 2018...run endTue Feb 06 15:53:20 CST 2018..run startTue Feb 06 15:53:23 CST 2018...run end
自訂線程池

如果Executors工廠類無法滿足我們的需求,可以自己去建立線程池。在自己建立線程池時,這個構造方法對於隊列是什麼類型比較關鍵:

使用有屆隊列(ArrayBlockingQueue):若有新的任務需要執行時,如果線程池實際線程數小於corePoolSize,則優先建立線程,若大於corePoolSize,則會將任務排入佇列中等待執行,若隊列已滿,則在匯流排程數不大於maximumPoolSize的前提下,建立行的線程,諾線程數大於maximumPoolSize,則執行拒絕策略。
使用無界隊列(LinkedBlockingQueue):除非系統資源耗盡,否則無界的任務隊列不存在入隊失敗的情況。當有新任務來時,系統的線程數小於corePoolSize時,則建立線程執行任務,當達到corePoolSize後,就不會繼續增加,若後續還有新的任務加入,而沒有閒置線程資源,則任務直接進入隊列等待。若任務建立和處理的速度差異很大時,無界隊列會保持快速增長,直到耗盡系統記憶體。注意:maximumPoolSize在無界隊列時沒有作用
JDK拒絕策略:
AbortPolicy:直接拋出異常組織系統正常工作CallerRunsPolicy:只要線程池未關閉,該策略直接在調用者線程中,運行當前被丟棄的任務
DiscardOldestPolicy:丟棄最老的一個請求,嘗試再次提交當前任務
DiscardPolicy:丟棄無法處理的任務,不做任何處理。
如果需要自訂拒絕策略可以實現RejectedExecutionHandler介面

有屆隊列的例子
public class UseThreadPoolExecutor1 {    public static void main(String[] args) {        /**         * 在使用有界隊列時,若有新的任務需要執行,如果線程池實際線程數小於corePoolSize,則優先建立線程,         * 若大於corePoolSize,則會將任務排入佇列,         * 若隊列已滿,則在匯流排程數不大於maximumPoolSize的前提下,建立新的線程,         * 若線程數大於maximumPoolSize,則執行拒絕策略。或其他自訂方式。         *          */            ThreadPoolExecutor pool = new ThreadPoolExecutor(                1,                 //coreSize                2,                 //MaxSize                60,             //60                TimeUnit.SECONDS,                 new ArrayBlockingQueue<Runnable>(3)            //指定一種隊列 (有界隊列)                //new LinkedBlockingQueue<Runnable>()//                , new MyRejected()                //, new DiscardOldestPolicy()                );                MyTask mt1 = new MyTask(1, "任務1");        MyTask mt2 = new MyTask(2, "任務2");        MyTask mt3 = new MyTask(3, "任務3");        MyTask mt4 = new MyTask(4, "任務4");        MyTask mt5 = new MyTask(5, "任務5");        MyTask mt6 = new MyTask(6, "任務6");                pool.execute(mt1);        pool.execute(mt2);        pool.execute(mt3);        pool.execute(mt4);        pool.execute(mt5);        pool.execute(mt6);                pool.shutdown();            }}
View Code

只執行前四個任務(把任務5,6先不執行)

run taskId =1run taskId =2run taskId =3run taskId =4

它是一個一個執行的,原因是第一個線程來的時候,立即執行了(coreSize=1),當後面三個線程來的時候會被加入到queue中(new ArrayBlockingQueue<Runnable>(3))

只執行前五個任務

run taskId =1run taskId =5run taskId =2run taskId =3run taskId =4

它是兩個兩個執行的,原因是第五個任務來的時候已經超出了queue的size(3),但是匯流排程數有小於MaxSize(2),所以任務5和任務1一起執行了,之後會從queue中拿兩個再執行

執行留個任務

run taskId =1Exception in thread "main" run taskId =5java.util.concurrent.RejectedExecutionException: Task 6 rejected from java.util.concurrent.ThreadPoolExecutor@4e25154f[Running, pool size = 2, active threads = 2, queued tasks = 3, completed tasks = 0]    at java.util.concurrent.ThreadPoolExecutor$AbortPolicy.rejectedExecution(ThreadPoolExecutor.java:2047)    at java.util.concurrent.ThreadPoolExecutor.reject(ThreadPoolExecutor.java:823)    at java.util.concurrent.ThreadPoolExecutor.execute(ThreadPoolExecutor.java:1369)    at com.bjsxt.height.concurrent018.UseThreadPoolExecutor1.main(UseThreadPoolExecutor1.java:46)run taskId =2run taskId =3run taskId =4

任務6來的時候,queue已經滿了,匯流排程數也滿了,這是會執行拒絕策略,JDK預設的是AbortPolicy,直接拋出異常,我們也可以改,就想代碼裡注釋掉的一樣

無界隊列的例子
public class UseThreadPoolExecutor2 implements Runnable{    private static AtomicInteger count = new AtomicInteger(0);        @Override    public void run() {        try {            int temp = count.incrementAndGet();            System.out.println("任務" + temp);            Thread.sleep(2000);        } catch (InterruptedException e) {            e.printStackTrace();        }    }        public static void main(String[] args) throws Exception{        //System.out.println(Runtime.getRuntime().availableProcessors());        BlockingQueue<Runnable> queue =                 new LinkedBlockingQueue<Runnable>();        ExecutorService executor  = new ThreadPoolExecutor(                    5,         //core                    10,     //max                    120L,     //2fenzhong                    TimeUnit.SECONDS,                    queue);                for(int i = 0 ; i < 20; i++){            executor.execute(new UseThreadPoolExecutor2());        }        Thread.sleep(1000);        System.out.println("queue size:" + queue.size());        //10        Thread.sleep(2000);    }}
View Code

執行結果:

任務1任務2任務3任務4任務5queue size:15任務6任務7任務9任務8任務10任務11任務12任務13任務14任務15任務16任務17任務19任務20任務18

任務是5個5個執行的,而且把剩餘的任務全部加到queue中。第二個參數沒有作用,不會建立10個線程,如果是有屆隊列,就會起作用。

Task的代碼:

public class MyTask implements Runnable {    private int taskId;    private String taskName;        public MyTask(int taskId, String taskName){        this.taskId = taskId;        this.taskName = taskName;    }        public int getTaskId() {        return taskId;    }    public void setTaskId(int taskId) {        this.taskId = taskId;    }    public String getTaskName() {        return taskName;    }    public void setTaskName(String taskName) {        this.taskName = taskName;    }    @Override    public void run() {        try {            System.out.println("run taskId =" + this.taskId);            Thread.sleep(5*1000);            //System.out.println("end taskId =" + this.taskId);        } catch (InterruptedException e) {            e.printStackTrace();        }            }        public String toString(){        return Integer.toString(this.taskId);    }}
View Code

 MyRejected的代碼:

public class MyRejected implements RejectedExecutionHandler{        public MyRejected(){    }        @Override    public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {        System.out.println("自訂處理..");        System.out.println("當前被拒絕任務為:" + r.toString());    }}
View Code

 

聯繫我們

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