你應該知道的ThreadPoolExecutor

爲什麼要有線程池來,可以參考這篇Blog Java線程實現原理

首先來簡單看下Java中兩種啓動線程的方式。

//Extends Thread
public class MyThread extends Thread {
    @Override
    public void run(){
        //TODO 
    }

    public void main(String[] args){
        new MyThread().start();
    }
}
// Implements Runnable
public class MyRunnable implements Runnable{
    @Override
    public void run(){
        //TODO
    }

    public void main(String[] args){
        new Thread(new MyRunnable()).start();
    }
}

第一種方式需要繼承一個Thread類,來擴展Thread的類的功能已達到運行自身邏輯的目的,從軟件設計上來看這種方式使用繼承來擴展功能,不是推薦的做法;從Java語言特性上來說,單繼承的規約限制了MyThread的對其他類的功能的複用。因此這種方式看似簡單,但是不是推薦啓動線程的方法。
第二種方式通過集成Runnable接口實現其run方法完成業務邏輯的編寫,並將MyRunnable的實例傳給一個Thread實例,並調用Thread實例的start方法進行線程的啓動。這種做法的好處是將邏輯功能與線程本事解耦出來,業務邏輯不用受到Thread的類的限制。因此這種方式算是比較合理的方式。
但是這兩種方式的一個共同特點是自己啓動一個Thread來運行,結合Java線程實現原理來看,Java的線程其實是映射爲Linux的一個內核線程來實現的,因而線程的個數也收到了限制,同事過多的啓動線程來完成任務也會找成CPU頻繁的進行上下文切換造成服務器不穩定,資源分配不合理。爲了解決這個問題Java線程池應允而生。

本文只介紹ThreadPoolExecutor因此本文涉及的類的繼承結構如下所示:
這裏寫圖片描述

兩個比較重要的類
Executors: 快速創建ThreadPoolExecutor的工具類
ThreadPoolExecutor: 這正的線程池實現者
廢話不說,先看一個實例。

public class ThreadPoolTest{
    private static ExecutorService executorService = Executors.newFixedThreadPool(5);

    public static void main(String[] args){
        executorService.execute(new MyRunnable());
    }   
}

怎麼樣使用起來簡單易懂。
在來看看ThreadPoolExecutor的構造方法

    /**
     * Creates a new {@code ThreadPoolExecutor} with the given initial
     * parameters.
     *
     * @param corePoolSize the number of threads to keep in the pool, even
     *        if they are idle, unless {@code allowCoreThreadTimeOut} is set
     * @param maximumPoolSize the maximum number of threads to allow in the
     *        pool
     * @param keepAliveTime when the number of threads is greater than
     *        the core, this is the maximum time that excess idle threads
     *        will wait for new tasks before terminating.
     * @param unit the time unit for the {@code keepAliveTime} argument
     * @param workQueue the queue to use for holding tasks before they are
     *        executed.  This queue will hold only the {@code Runnable}
     *        tasks submitted by the {@code execute} method.
     * @param threadFactory the factory to use when the executor
     *        creates a new thread
     * @param handler the handler to use when execution is blocked
     *        because the thread bounds and queue capacities are reached
     * @throws IllegalArgumentException if one of the following holds:<br>
     *         {@code corePoolSize < 0}<br>
     *         {@code keepAliveTime < 0}<br>
     *         {@code maximumPoolSize <= 0}<br>
     *         {@code maximumPoolSize < corePoolSize}
     * @throws NullPointerException if {@code workQueue}
     *         or {@code threadFactory} or {@code handler} is null
     */
public ThreadPoolExecutor(int corePoolSize,
                          int maximumPoolSize,
                          long keepAliveTime,
                          TimeUnit unit,
                          BlockingQueue<Runnable> workQueue,
                          ThreadFactory threadFactory,
                          RejectedExecutionHandler handler) 

註釋已經對這些參數解釋的足夠清晰,但是要真是使用起來,new出一個ThreadPoolExecutor實例也是比較麻煩的,好在Executors工具類提供了三個適合常見場景的工廠方法,使用起來非常方便快捷。

public static ExecutorService newFixedThreadPool(int nThreads);
public static ExecutorService newSingleThreadExecutor();
public static ExecutorService newCachedThreadPool();
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章