package com.dy.pool; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; /** * ExecutorService 真正的線程池接口。 ScheduledExecutorService 能和Timer/TimerTask相似,解決那些須要任務重複執行的問題。 ThreadPoolExecutor是ExecutorService的默認實現。 ScheduledThreadPoolExecutor繼承ThreadPoolExecutor的ScheduledExecutorService接口實現,週期性任務調度的類實現。 * 在Executors類裏面提供了一些靜態工廠,生成一些經常使用的線程池。 * 2.newFixedThreadPool 建立固定大小的線程池。每次提交一個任務就建立一個線程,直到線程達到線程池的最大大小。 線程池的大小一旦達到最大值就會保持不變,若是某個線程由於執行異常而結束,那麼線程池會補充一個新線程 */ public class FixedThreadPool { public static void main(String[] args) { System.out.println("歡迎來到線程世界!"); //建立一個可重用固定線程數的線程池 ExecutorService pool = Executors.newFixedThreadPool(2); //建立實現了Runnable接口對象,Thread對象固然也實現了Runnable接口 FixedThreadPool.MyThread t1 = new FixedThreadPool().new MyThread(); FixedThreadPool.MyThread t2 = new FixedThreadPool().new MyThread(); FixedThreadPool.MyThread t3 = new FixedThreadPool().new MyThread(); FixedThreadPool.MyThread t4 = new FixedThreadPool().new MyThread(); //將線程放入池中進行執行 pool.execute(t1); pool.execute(t2); pool.execute(t3); pool.execute(t4); //關閉線程池 pool.shutdown(); } class MyThread extends Thread { @Override public void run() { System.out.println(Thread.currentThread().getName() + "正在執行。。。"); } } }
另外說下 代碼中的this.getName和Thread.currentThread().getName(): java
前者的this是指實例對象自身,後者是指實例對象中的當前執行線程;兩者不要理解混淆了! ide
類模型: this