Java多線程之線程池

  如今是多核的時代,面向多核的編程很重要,所以基於java的併發和多線程開發很是重要。java

  線程池是於隊列密切相關的,其中隊列保存了全部等待執行的任務。工做者線程的任務很簡單:從隊列中獲取一個任務,執行任務,而後返回線程池,等待下一個任務。spring

  在線程池中執行任務,比爲每個任務分配一個線程優點更多:編程

    1.經過重用如今的線程,而不是建立線程,能夠在處理多個請求時避免在線程的建立和銷燬上的開銷。緩存

    2.當請求到達時,工做線程一般已經存在,所以不會猶豫等待建立線程而延遲任務的執行,從而提升響應。多線程

    3.經過適當的調整線程池的大小,能夠建立足夠多的線程使處理器保持忙碌狀態,同時也能夠防止過多線程競爭資源而使應用程序的內存耗盡或失敗。併發

 

  1.配置ThreadPoolExecutorless

    類庫提供了一個靈活的線程池以及一些有用的默認配置,能夠經過調用Executors中的靜態工廠方法來建立:函數

      newFixedThreadPool:建立一個固定長度的線程池,沒提交一個任務就建立一個線程,直到到達線程池的最大數量,這時線程池的規模將再也不變化。this

      newCachedThreadPool:建立一個可緩存的線程池,若是線程的當前規模超過處理的需求時,將回收空閒線程,當需求增長時候,能夠添加新的線程,線程池的規模不存在任何限制(不建議使用,若是處理量過多,會由於建立過多線程致使資源耗盡)spa

      newSingleThreadPool: 是一個單線程的Executor。

      newScheduledThreadPool:建立一個固定長度的線程池,並且以延遲或者定時的方式來執行。

  若是默認的執行策略不知足要求,那麼能夠經過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)

其中corePoolSize爲線程池的基本大小,maximumPoolSize爲最大大小。RejectedExecutionHandler爲飽和策略,當有界隊列被填滿以後,採用什麼方式來處理。有四種處理方式

 

 

 若是項目中使用Spring,可使用spring提供的的線程池管理的包裝類ThreadPoolTaskExecutor,它對標準的java.util.concurrent.ThreadPoolExecutor進行了封裝,配置和使用比較簡單

 

  

<bean id="threadPool" 
class="org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor">
    <property name="corePoolSize" value="5" />
    <property name="maxPoolSize" value="10" />
    <property name="keepAliveSeconds" value="5" />
    <property name="queueCapacity" value="2000" />
    <property name="rejectedExecutionHandler">
        <bean                 class="java.util.concurrent.ThreadPoolExecutor$AbortPolicy" />
    </property>
</bean>

corePoolSize:核心線程數,默認爲1

maxPoolSize:最大線程數,默認爲Integer.MAX_VALUE

keepAliveSeconds:線程池維護線程所容許的空閒時間,默認爲60s

queueCapacity:隊列最大長度,默認爲Integer.MAX_VALUE

rejectedExecutionHandler:線程池對拒絕任務(超過待處理隊列長度)的處理策略

AbortPolicy:表示直接拋出RejectedExecutionException異常  

使用:

threadPool.execute(new Runnable() {
  public void run() {
    try{
    ......
    }catch(Exception e){
    ......
    }
  }
});
相關文章
相關標籤/搜索