ThreadPoolExecutor pool = new ThreadPoolExecutor(1//核心線程數量
, 3//最大線程數量
, 60//線程存活時間
, TimeUnit.SECONDS,
new ArrayBlockingQueue<>(2)//有界隊列
, new ThreadFactory() {
@Override
public Thread newThread(Runnable r) {
Thread th = new Thread(r,"my_thread");
if(th.getPriority() != Thread.NORM_PRIORITY){
th.setPriority(Thread.NORM_PRIORITY);
}
if(th.isDaemon()){
th.setDaemon(false);
}
return th;
}
}, new RejectedExecutionHandler() {
@Override
public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
System.err.println("當前任務已經被拒絕:"+r);
}
});
Task t1 = new Task(1,1);
Task t2 = new Task(2,2);
Task t3 = new Task(3,3);
Task t4 = new Task(4,4);
Task t5 = new Task(5,5);
Task t6 = new Task(6,6);
pool.execute(t1);
pool.execute(t2);
pool.execute(t3);
pool.execute(t4);
pool.execute(t5);
pool.execute(t6);
pool.shutdown();
public class Task implements Runnable{
private int id;
private int count;
public Task(int id, int count) {
super();
this.id = id;
this.count = count;
}
@Override
public void run() {
System.err.println("處理線程任務:" + this.id);
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
@Override
public String toString() {
return "Task [id=" + id + ", count=" + count + "]";
}
}
從代碼的運行結果來看
處理線程任務:1
處理線程任務:5
處理線程任務:4
當前任務已經被拒絕:Task [id=6, count=6]
處理線程任務:2
處理線程任務:3
當執行線程t1的時候,直接使用初始化的核心線程執行任務
當執行線程t2的時候,此時線程的數量大於核心線程,則講t2線程加入有界隊列中
當執行線程t3的時候,此時線程的數量大於核心線程 ,則t3線程加入有界隊列中
當執行線程t4的時候,此時隊列容量已滿,此時的線程數量是還沒有超過最大線程,則啓用一個新的線程執行任務
當執行線程t5的時候,此時隊列容量已滿,此時的線程數量是還沒有超過最大線程,則啓用一個新的線程執行任務
當執行線程t6的時候,此時隊列容量已滿,此時的線程數量超過最大線程,則啓用自己的拒絕策略
注意的是,如果把ArrayBlockingQueue 有界隊列,換成無界隊列LinkedBlockingQueue 則線程池的工作原理是
當線程的數量不超過核心線程的數量,啓用線程去執行任務,當線程數量大於核心線程的數量的時候,則直接加入無界隊列中等待被執行,此時後的最大線程數量的設置其實是沒有作用的