工廠方法設計模式是面向對象編程中最經常使用的設計模式之一,工廠方法屬於建立類型,主要用來建立對象;java
使用工廠方法建立對象有幾個有點:編程
Java提供了ThreadFactory 接口用來實現工廠方法建立線程;設計模式
1.實現一個工廠方法app
public class MyThreadFactory implements ThreadFactory { private AtomicInteger threadNumber = new AtomicInteger(0); // Store thread name private String name; // Store statistical data about the Thread object created private List<String> stats; private ThreadGroup group; public MyThreadFactory(String name) { this.name = name; stats = new ArrayList<>(); SecurityManager s = System.getSecurityManager(); group = (s != null) ? s.getThreadGroup() : Thread.currentThread().getThreadGroup(); } @Override public Thread newThread(Runnable r) { Thread t = new Thread(group,r, name + "-Thread_" + threadNumber.getAndIncrement()); if (t.isDaemon()) t.setDaemon(false); if (t.getPriority() != Thread.NORM_PRIORITY) t.setPriority(Thread.NORM_PRIORITY); stats.add(String.format("Created thread %d with name %s in group %s, on %s\n", t.getId(), t.getName(),t.getThreadGroup().getName(), Utils.dateFormat(new Date()))); return t; } public String getStats() { StringBuffer buffer = new StringBuffer(); for (String stat : stats) { buffer.append(stat); buffer.append("\n"); } return buffer.toString(); } }
public class Task implements Runnable { @Override public void run() { try { TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); } } public static void main(String[] args) { MyThreadFactory threadFactory = new MyThreadFactory("MyThreadFactory"); Task task=new Task(); Thread thread; System.out.printf("Starting the Threads\n"); for (int i=0; i<10; i++){ thread=threadFactory.newThread(task); thread.start(); } System.out.printf("Factory stats:\n"); System.out.printf("%s\n",threadFactory.getStats()); } }
ThreadFactory 接口提供了newThread方法,用來建立線程,在這個方法裏,對於建立的線程咱們能夠加入一些更多的控制;工廠方法和靜態工廠方法是不同的,具體區別之後記錄;ide