- package com.nankang.test.thread;
- import java.util.concurrent.ExecutorService;
- import java.util.concurrent.Executors;
- import java.util.concurrent.LinkedBlockingQueue;
- import java.util.concurrent.ThreadPoolExecutor;
- import java.util.concurrent.TimeUnit;
- /**
- *
- * @author qianguangtao
- * 第2次任務的第1次執行
- * 第1次任務的第1次執行
- * 第3次任務的第1次執行
- * 第2次任務的第2次執行
- * 第3次任務的第2次執行
- * 第1次任務的第2次執行
- * 第2次任務的第3次執行
- * 第1次任務的第3次執行
- * 第3次任務的第3次執行
- * 第2次任務的第4次執行
- * 第3次任務的第4次執行
- * 第1次任務的第4次執行
- * 第4次任務的第1次執行
- * 第4次任務的第2次執行
- * 第4次任務的第3次執行
- * 第4次任務的第4次執行
- */
- public class TestFixedPool {
- public static void main(String[] args) {
- // ThreadPoolExecutor threadPool = (ThreadPoolExecutor)
- // Executors.newCachedThreadPool(); //core 大小:0 max 大小:2147483647
- // ThreadPoolExecutor threadPool = (ThreadPoolExecutor)
- // Executors.newFixedThreadPool(3); //core 大小:3 max 大小:3
- ThreadPoolExecutor threadPool = (ThreadPoolExecutor) Executors
- .newScheduledThreadPool(3); // core 大小:3 max 大小:2147483647
- System.out.println("core 大小:" + threadPool.getCorePoolSize()
- + " max 大小:" + threadPool.getMaximumPoolSize());
- /*
- * 其實 newFixedThreadPool 是創建了一個 ThreadPoolExecutor return new
- * ThreadPoolExecutor(3[corePoolSize], 3[maximumPoolSize], 0L,
- * TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>()); 當
- * corePoolSize 和 maximumPoolSize 大小一樣時,即爲 newFixedThreadPool
- */
- for (int i = 1; i < 5; i++) {
- final int taskID = i;
- threadPool.execute(new Runnable() {
- // 也就是說最外層的 for 循環式正常運行的,execute 方法裏面的 for循環不一定立即執行
- // execute(thread); 在未來的某個時間執行給定命令。該命令可能在新的線程,已入池的線程,後者正在調用的線程中執行,由Executor實現決定
- public void run() {
- for (int i = 1; i < 5; i++) {
- System.out.println("第" + taskID + "次任務的第" + i + "次執行");
- try {
- Thread.sleep(2000);// 爲了測試出效果,讓每次任務執行都需要一定時間
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- }
- });
- }
- threadPool.shutdown();// 任務執行完畢,關閉線程池 ,線程池會自動關閉,即使沒有調用 shutdown();
- }
- }