java ThreadPoolExecutor 自定義線程池demo

版權聲明:本文爲博主原創文章,未經博主允許不得轉載。 https://blog.csdn.net/woshimike/article/details/53906382

package com.lyq.jsoup.concurrent.threadpool;
import java.util.concurrent.TimeUnit;

/**
 * Created by mike on 2016/12/28.
 */
public class TestThreadPoolTask implements Runnable {

    private int id ;
    private String name;

    public TestThreadPoolTask(int id, String name) {
        this.id = id;
        this.name = name;
    }

    @Override
    public void run() {
        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(Thread.currentThread().getName() + ",id:" +this.id);
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}


package com.lyq.jsoup.concurrent.threadpool;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * Created by mike on 2016/12/28.
 */
public class TestThreadPool {
    public static void main(String[] args){
        ArrayBlockingQueue<Runnable> arrayWorkQueue = new ArrayBlockingQueue(10);
        LinkedBlockingDeque<Runnable> linkedWorkQueue = new LinkedBlockingDeque();
        int count = 20;
        ExecutorService threadPool = new ThreadPoolExecutor(5, //corePoolSize線程池中核心線程數
                10, //maximumPoolSize 線程池中最大線程數
                60, //線程池中線程的最大空閒時間,超過這個時間空閒線程將被回收
                TimeUnit.SECONDS,//時間單位
                //下面是採用有界隊列和無界隊列的區別
                arrayWorkQueue,
                //linkedWorkQueue,

                //下面是jdk的四種執行策略
                //new ThreadPoolExecutor.AbortPolicy()  這種策略直接拋出異常,丟棄任務。
                //new ThreadPoolExecutor.DiscardPolicy() 這種策略和AbortPolicy幾乎一樣,也是丟棄任務,只不過他不拋出異常。
                //new ThreadPoolExecutor.CallerRunsPolicy() //線程調用運行該任務的 execute 本身。此策略提供簡單的反饋控制機制,能夠減緩新任務的提交速度。沒看明白,當時是我的main線程執行的task5
                new ThreadPoolExecutor.DiscardOldestPolicy()//如果執行程序尚未關閉,則位於工作隊列頭部的任務將被刪除,然後重試執行程序(如果再次失敗,則重複此過程)
        );

        for (int i = 1; i <= count ;i++){
            TestThreadPoolTask task = new TestThreadPoolTask(i,"name"+i);
            threadPool.execute(task);
        }

        threadPool.shutdown();

    }
}


通過上面的小demo可以總結規律
1:如果自定義隊列是有界隊列:
當線程池中的任務數 > maximumPoolSize時,線程池會自動創建線程,直到 線程數 = maximumPoolSize;
如果這個時候線程池任務還 > maximumPoolSize, 線程池就會把任務放到任務隊列中;
如果隊列滿了採用配置的拒絕策略
2:如果自定義隊列是無解隊列:
 maximumPoolSize 參數無效,線程池中就只有corePoolSize個線程執行任務。知道系統崩潰(內存溢出,由於是無解隊列)
  3:拒絕策略建議採用自定義拒絕策略

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章