工廠模式是面向對象編程中最常使用的模式之一,它是個建立者模式,使用一個類爲其餘的一個或者多個類建立對象。當咱們要爲這些類建立對象時,不需再使用 new 構造器,而是使用工廠類。java
好處:編程
一、更容易修改類,或者改變建立對象的方式。ide
二、更容易爲有限資源限制建立對象的數目。如:能夠限制一個類型的對象很少於 n 個。this
三、更容易爲建立的對象生成統計數據。spa
實現 ThreadFactory 接口 :線程
import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.concurrent.ThreadFactory; /** * 實現 ThreadFactory 接口 來 自定義 建立線程的工程類 */ public class MyThreadFactory implements ThreadFactory{ SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"); private int counter; private String name; private List<String> stas; // 存放線程對象的 統計性數字 public MyThreadFactory(String name) { counter = 0; this.name = name; stas = new ArrayList<String>(); } @Override public Thread newThread(Runnable r) { Thread thread = new Thread(r, name+"-thread-"+counter); counter++; stas.add("線程:id-"+thread.getId()+",name:" + thread.getName() + "," + sdf.format(new Date()) + "被建立..."); return thread; } //表示全部的數據 public void getStas(){ if(stas == null || stas.size() == 0){ System.out.println("未進行線程建立操做.."); return; } for(String s : stas){ System.out.println(s); } } }
import java.util.concurrent.TimeUnit; public class PrintTask implements Runnable{ public void run() { try { System.out.println(Thread.currentThread().getName() +"- 任務 test"); TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); } } }
public class MyThreadFactoryTest { public static void main(String[] args) { PrintTask printTask = new PrintTask(); MyThreadFactory myThreadFactory = new MyThreadFactory("myThreadFactory"); for(int i=0;i<3;i++){ Thread thread = myThreadFactory.newThread(printTask); thread.start(); try { thread.join(); // 主線程 等待 子線程完成後繼續. } catch (InterruptedException e) { e.printStackTrace(); } } myThreadFactory.getStas(); System.out.println(Thread.currentThread().getName() + " -> 結束.."); } }
//console 結果: myThreadFactory-thread-0- 任務 test myThreadFactory-thread-1- 任務 test myThreadFactory-thread-2- 任務 test 線程:id-11,name:myThreadFactory-thread-0,2017-09-07 09:40:20被建立... 線程:id-12,name:myThreadFactory-thread-1,2017-09-07 09:40:21被建立... 線程:id-13,name:myThreadFactory-thread-2,2017-09-07 09:40:22被建立... main -> 結束..