關於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) 
我的自定義註解
  1. corePoolSize:核心線程池大小(核心線程數量)
  2. maximumPoolSize:最大線程池大小
  3. keepAliveTime :線程最大空閒時間
  4. unit :keepAliveTime 時間單位
  5. workQueue :線程等待隊列
  6. threadFactory :線程創建工廠
  7. handler :拒絕策略
ThreadPoolExecutor的執行順序

在這裏插入圖片描述

二 、使用案例

(自定義線程工廠,自定義拒絕策略)
package com.wx;

import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

public class ThreadTest {
    public static void main(String[] args) {
        int corePoolSize = 3;
        int maximumPoolSize = 3;
        long keepAliveTime = 10;
        TimeUnit unit = TimeUnit.SECONDS;
        BlockingQueue<Runnable> workQueue = new ArrayBlockingQueue<>(2);
        ThreadFactory threadFactory = new MyThreadFactory();
//        RejectedExecutionHandler handler = new MyIgnorePolicy();
        RejectedExecutionHandler handler = new ThreadPoolExecutor.CallerRunsPolicy();
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
                corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, threadFactory, handler);

        threadPoolExecutor.prestartAllCoreThreads(); // 預啓動所有核心線程

        for (int i = 0; i <= 10; i++) {
            MyTask task = new MyTask(String.valueOf(i));
            threadPoolExecutor.execute(task);
        }

    }

    static class MyThreadFactory implements ThreadFactory{
        private AtomicInteger atomicInteger = new AtomicInteger(0);

        @Override
        public Thread newThread(Runnable r) {
            Thread thread = new Thread(r,"wxThread-"+atomicInteger.getAndIncrement());
            System.out.println(">>>>>>>>"+thread.getName()+" has been created !");
            return thread;
        }
    }

    static class MyIgnorePolicy  implements RejectedExecutionHandler{

        @Override
        public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
            System.err.println(r.toString()+"rejected");
//            System.out.println("completedTaskCount: " + executor.getCompletedTaskCount());
        }
    }

    static class MyTask implements Runnable{
        private String name;

        public MyTask(String name) {
            this.name = name;
        }

        public String getName() {
            return name;
        }

        @Override
        public String toString() {
            return "MyTask{" +
                    "name='" + name + '\'' +
                    '}';
        }

        @Override
        public void run() {
            try {
                System.out.println(this.toString() + " is running!");
                Thread.sleep(300); //讓任務執行慢點
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

}


AbortPolicy:默認測策略,拋出RejectedExecutionException運行時異常;
CallerRunsPolicy:這提供了一個簡單的反饋控制機制,可以減慢提交新任務的速度;
DiscardPolicy:直接丟棄新提交的任務;
DiscardOldestPolicy:如果執行器沒有關閉,隊列頭的任務將會被丟棄,然後執行器重新嘗試執行任務(如果失敗,則重複這一過程);

發佈了11 篇原創文章 · 獲贊 2 · 訪問量 2716
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章