第十四章 Executors源碼解析,executors源碼

來源:互聯網
上載者:User

第十四章 Executors源碼解析,executors源碼

前邊兩章介紹了基礎線程池ThreadPoolExecutor的使用方式、工作機理、參數詳細介紹以及核心源碼解析。

具體的介紹請參照:

第十二章 ThreadPoolExecutor使用與工作機理

第十三章 ThreadPoolExecutor源碼解析

1、Executors與ThreadPoolExecutor

  • ThreadPoolExecutor
    • 可以靈活的自訂的建立線程池,可定製性很高
    • 想建立好一個合適的線程池比較難
    • 使用稍微麻煩一些
    • 實際中很少使用
  • Executors
    • 可以建立4種線程池,這四種線程池基本上已經包含了所有需求,將來根據業務特點選用就好
    • 使用非常簡單
    • 實際中很常用

 使用方法:

package com.collection.test;import java.util.concurrent.Executor;import java.util.concurrent.Executors;public class ThreadPoolExecutorTest { //private static ThreadPoolExecutor executor = new ThreadPoolExecutor(5, 10, 30, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(10)); //private static Executor executor = Executors.newFixedThreadPool(5); //private static Executor executor = Executors.newSingleThreadExecutor(); //private static Executor executor = Executors.newCachedThreadPool(); private static Executor executor = Executors.newScheduledThreadPool(5); public void executeTask(){ Task1 task1 = new Task1();//構建任務1 Task2 task2 = new Task2();//構建任務2 executor.execute(task1);//執行任務1 executor.execute(task2);//執行任務2 } /* * 基本任務2 */ class Task1 implements Runnable{ public void run() { //具體任務的業務 for(int i=0;i<1000;i++){ System.out.println("hello xxx!!!"); } } } /* * 基本任務2 */ class Task2 implements Runnable{ public void run() { //具體任務的業務 for(int i=0;i<5;i++){ System.out.println("hello world2!!!"); } } } public static void main(String[] args) { ThreadPoolExecutorTest test = new ThreadPoolExecutorTest(); test.executeTask(); }}View Code

 

2、Executors可以建立的幾種線程池簡介

  • newFixedThreadPool(int corePoolSize)
    • 建立一個線程數固定(corePoolSize==maximumPoolSize)的線程池
    • 核心線程會一直運行
    • 無界隊列LinkedBlockingQueue
  • newSingleThreadExecutor
    • 建立一個線程數固定(corePoolSize==maximumPoolSize==1)的線程池
    • 核心線程會一直運行
    • 無界隊列LinkedBlockingQueue
    • 所有task都是串列執行的(即同一時刻只有一個任務在執行)
  • newCachedThreadPool
    • corePoolSize==0
    • maximumPoolSize==Integer.MAX_VALUE
    • 隊列:SynchronousQueue
    • 建立一個線程池:當池中的線程都處於忙碌狀態時,會立即建立一個線程來處理新來的任務
    • 這種池將會在執行許多耗時短的非同步任務的時候提高程式的效能
    • 6秒鐘內沒有使用的線程將會被中止,並且從線程池中移除,因此幾乎不必擔心耗費資源
  • newScheduledThreadPool(int corePoolSize)
    • 用於執行定時或順延強制的任務,最典型的:非同步作業時的逾時回調

注意:對於定時任務的執行,在實際使用中,會去使用spring定時器,非常方便

 

3、newFixedThreadPool(int corePoolSize)

原始碼:

/** * 1、建立一個線程數固定(corePoolSize==maximumPoolSize)的線程池, * 2、核心線程會一直運行 * 3、無界隊列LinkedBlockingQueue */ public static ExecutorService newFixedThreadPool(int nThreads) { return new ThreadPoolExecutor(nThreads, nThreads, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>()); }View Code

說明:execute()的原始碼查看第十三章 ThreadPoolExecutor源碼解析

 

4、newSingleThreadExecutor()

原始碼:

/** * 1、建立一個線程數固定(corePoolSize==maximumPoolSize==1)的線程池 * 2、核心線程會一直運行 * 3、無界隊列LinkedBlockingQueue * 注意:所有task都是串列執行的 */ public static ExecutorService newSingleThreadExecutor() { return new FinalizableDelegatedExecutorService (new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>())); }View Code

說明:execute()的原始碼查看第十三章 ThreadPoolExecutor源碼解析

 

5、newCachedThreadPool()

原始碼:

/** * 1、建立一個線程池:當池中的線程都處於忙碌狀態時,會立即建立一個線程來處理新來的任務 * 2、這種池將會在執行許多耗時短的非同步任務的時候提高程式的效能。 * 3、6秒鐘內沒有使用的線程將會被中止,並且從線程池中移除,因此幾乎不必擔心耗費資源 * 4、隊列:SynchronousQueue * 5、maximumPoolSize為Integer.MAX_VALUE */ public static ExecutorService newCachedThreadPool() { return new ThreadPoolExecutor(0, Integer.MAX_VALUE, 60L, TimeUnit.SECONDS, new SynchronousQueue<Runnable>()); }View Code

說明:execute()的原始碼查看第十三章 ThreadPoolExecutor源碼解析

 

6、newScheduledThreadPool(int corePoolSize)

原始碼:

Executors:newScheduledThreadPool(int corePoolSize)

/** * 建立一個線程池:該線程池可以用於執行延時任務或者定時任務 */ public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize) { return new ScheduledThreadPoolExecutor(corePoolSize); }View Code

ScheduledThreadPoolExecutor:ScheduledThreadPoolExecutor(int corePoolSize)

/** * 建立一個線程池: * corePoolSize==我們指定 * maximumPoolSize==Integer.MAX_VALUE * keepAliveTime==0納秒(即不回收閑置線程) * 隊列: DelayedWorkQueue */ public ScheduledThreadPoolExecutor(int corePoolSize) { super(corePoolSize, Integer.MAX_VALUE, 0, TimeUnit.NANOSECONDS, new DelayedWorkQueue()); }View Code

說明:ScheduledThreadPoolExecutor是ThreadPoolExecutor的子類,其中調用的super構造器就是ThreadPoolExecutor的構造器。

ScheduledThreadPoolExecutor:execute(Runnable command)

public void execute(Runnable command) { if (command == null) throw new NullPointerException(); schedule(command, 0, TimeUnit.NANOSECONDS); }View Code

ScheduledThreadPoolExecutor:schedule(Runnable command, long delay, TimeUnit unit)

/** * 這個方法:其實就是將task封裝一下,然後加入到DelayedWorkQueue中 * 1、DelayedWorkQueue其實就是一個DelayQueue * 2、當有新的task加入時,DelayQueue會將其加入內部的數組對象中,並對其進行排序,在這裡,排序的規則就是執行的時間,執行時間越近的排在越前 * 3、線程池中的線程在執行task時,擷取最近要執行的task,然後喚醒所有等待available條件的線程來執行該任務 */ public ScheduledFuture<?> schedule(Runnable command, long delay, TimeUnit unit) { if (command == null || unit == null) throw new NullPointerException(); RunnableScheduledFuture<?> t = decorateTask(command, new ScheduledFutureTask<Void>(command, null, triggerTime(delay, unit))); delayedExecute(t); return t; }View Code

注意:這裡的注釋就是整個ScheduledThreadPoolExecutor的執行機理。

 

下面說一下其中調用到的一些方法。

第一部分:封裝ScheduledFutureTask任務

ScheduledThreadPoolExecutor:triggerTime(long delay, TimeUnit unit)

/** * 返回一個delayed action(延時任務)的觸發時間 */ private long triggerTime(long delay, TimeUnit unit) { return triggerTime(unit.toNanos((delay < 0) ? 0 : delay)); } /** * Returns the trigger time of a delayed action. */ long triggerTime(long delay) { return now() + ((delay < (Long.MAX_VALUE >> 1)) ? delay : overflowFree(delay)); }View Code

說明:用於計算延時任務的觸發時間。

注意:在上邊的execute()方法中傳遞的delay是0,根據上邊的代碼,計算出觸發時間就是now()。

ScheduledThreadPoolExecutor:內部類ScheduledFutureTask

private class ScheduledFutureTask<V> extends FutureTask<V> implements RunnableScheduledFuture<V> { private final long sequenceNumber;//用於打破FIFO關係的序號 private long time;//任務執行的觸發時間 /** * 一個用於重複執行的任務的時間段(單位:納秒) * 0-->不重複執行的任務 * 正值:fixed-rate執行 * 負值:fixed-delay執行 */ private final long period; /** * 建立一個一次性的action並且指定觸發時間 */ ScheduledFutureTask(Runnable r, V result, long ns) { super(r, result); this.time = ns; this.period = 0; this.sequenceNumber = sequencer.getAndIncrement(); }View Code

說明:ScheduledFutureTask是FutureTask的子類,上邊的構造器中的super(r, result)代碼如下:

FutureTask:FutureTask(Runnable runnable, V result)

private final Sync sync;//控制FutureTask的同步器 public FutureTask(Runnable runnable, V result) { sync = new Sync(Executors.callable(runnable, result)); }View Code

Executors:callable(Runnable task, T result)

public static <T> Callable<T> callable(Runnable task, T result) { if (task == null) throw new NullPointerException(); return new RunnableAdapter<T>(task, result); }View Code

Executors:內部類RunnableAdapter

static final class RunnableAdapter<T> implements Callable<T> { final Runnable task; final T result; RunnableAdapter(Runnable task, T result) { this.task = task; this.result = result; } public T call() { task.run();//這裡是真正的task啟動並執行地方 return result; } }View Code

注意:這裡才是task真正去啟動並執行地方。-->task.run()

至此,ScheduledFutureTask任務封裝完成。

 

第二部分:修飾任務

ScheduledThreadPoolExecutor:RunnableScheduledFuture

protected <V> RunnableScheduledFuture<V> decorateTask(Runnable runnable, RunnableScheduledFuture<V> task) { return task; }View Code

說明:這裡其實就是直接返回了剛剛封裝好的任務

 

第三部分:將延時任務加入阻塞隊列

ScheduledThreadPoolExecutor:delayedExecute(Runnable command)

private void delayedExecute(Runnable command) { if (isShutdown()) {//return runState != RUNNING;線程池狀態不是RUNNING reject(command);//回絕任務 return; } if (getPoolSize() < getCorePoolSize())//當前線程池數量少於核心線程數 prestartCoreThread();//建立並啟動一個核心線程 super.getQueue().add(command);//擷取阻塞隊列,並將command排入佇列 }View Code

說明:這樣之後,之前封裝好的任務就加入了延時隊列DelayQueue(阻塞隊列的一個子類)

DelayQueue:add(E e)

public boolean add(E e) { return offer(e); } public boolean offer(E e) { final ReentrantLock lock = this.lock; lock.lock(); try { E first = q.peek();//擷取隊列頭部節點但不刪除 q.offer(e);//將e放到q的尾部 //如果隊列中只有e或者e的觸發時間小於隊頭結點 if (first == null || e.compareTo(first) < 0) available.signalAll(); return true; } finally { lock.unlock(); } }View Code

說明:在該方法中,將上邊封裝好的任務就加入了DelayQueue,並將該任務置於了隊頭,然後喚醒所有等待available條件的線程來執行該任務。

 

總結:

  • 四種線程池最常用的就是newCachedThreadPool和newFixedThreadPool(int corePoolSize)
  • 對於newScheduledThreadPool(int corePoolSize)使用比較少,因為在現代開發中,如果用於去開發定時任務程式的話,用spring定時器會非常簡單

 

聯繫我們

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