一、源碼分析
ThreadFactory是一個線程工廠。用來創建線程。這里為什么要使用線程工廠呢?其實就是為了統一在創建線程時設置一些參數,如是否守護線程。線程一些特性等,如優先級。通過這個TreadFactory創建出來的線程能保證有相同的特性。它首先是一個接口類,而且方法只有一個。就是創建一個線程。
public interface ThreadFactory { Thread newThread(Runnable r); }
1》ThreadPoolExecutor創建
public ThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue) { this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, Executors.defaultThreadFactory(), defaultHandler); }
最終均會調用創建以下構造方法

public ThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue, ThreadFactory threadFactory, RejectedExecutionHandler handler) { if (corePoolSize < 0 || maximumPoolSize <= 0 || maximumPoolSize < corePoolSize || keepAliveTime < 0) throw new IllegalArgumentException(); if (workQueue == null || threadFactory == null || handler == null) throw new NullPointerException(); this.acc = System.getSecurityManager() == null ? null : AccessController.getContext(); this.corePoolSize = corePoolSize; this.maximumPoolSize = maximumPoolSize; this.workQueue = workQueue; this.keepAliveTime = unit.toNanos(keepAliveTime); this.threadFactory = threadFactory; this.handler = handler; }
2》查看 Executors.defaultThreadFactory()實現
public static ThreadFactory defaultThreadFactory() { return new DefaultThreadFactory(); }
在JDK中,有實現ThreadFactory就只有一個地方。而更多的時候,我們都是繼承它然后自己來寫這個線程工廠的。
下面的代碼中在類Executors當中。默認的 我們創建線程池時使用的就是這個線程工廠
static class DefaultThreadFactory implements ThreadFactory { private static final AtomicInteger poolNumber = new AtomicInteger(1);//原子類,線程池編號 private final ThreadGroup group;//線程組 private final AtomicInteger threadNumber = new AtomicInteger(1);//線程數目 private final String namePrefix;//為每個創建的線程添加的前綴 DefaultThreadFactory() { SecurityManager s = System.getSecurityManager(); group = (s != null) ? s.getThreadGroup() : Thread.currentThread().getThreadGroup();//取得線程組 namePrefix = "pool-" + poolNumber.getAndIncrement() + "-thread-"; } public Thread newThread(Runnable r) { Thread t = new Thread(group, r, namePrefix + threadNumber.getAndIncrement(), 0);//真正創建線程的地方,設置了線程的線程組及線程名 if (t.isDaemon()) t.setDaemon(false); if (t.getPriority() != Thread.NORM_PRIORITY)//默認是正常優先級 t.setPriority(Thread.NORM_PRIORITY); return t; } }
在上面的代碼中,可以看到線程池中默認的線程工廠實現是很簡單的,它做的事就是統一給線程池中的線程設置線程group、統一的線程前綴名。以及統一的優先級。
2、以下是自己實現ThreadFactory示例

package com.func.axc.threadfactory; import java.util.ArrayList; import java.util.Date; import java.util.Iterator; import java.util.List; import java.util.concurrent.ThreadFactory; /** */ public class ThreadFactoryTest { static class MyThreadFactory implements ThreadFactory { private int counter; private String name; private List<String> stats; public MyThreadFactory(String name) { counter = 0; this.name = name; stats = new ArrayList<String>(); } @Override public Thread newThread(Runnable run) { Thread t = new Thread(run, name + "-Thread-" + counter); counter++; stats.add(String.format("Created thread %d with name %s on%s\n",t.getId(), t.getName(), new Date())); return t; } public String getStas() { StringBuffer buffer = new StringBuffer(); Iterator<String> it = stats.iterator(); while (it.hasNext()) { buffer.append(it.next()); buffer.append("\n"); } return buffer.toString(); } } static class MyTask implements Runnable { private int num; public MyTask(int num) { this.num = num; } @Override public void run() { System.out.println("Task "+ num+" is running"); try { Thread.sleep(2*10000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } public static void main(String[] args) { System.out.println("main thread beging"); MyThreadFactory factory = new MyThreadFactory("MyThreadFactory"); Thread thread = null; for(int i = 0; i < 10; i++) { thread = factory.newThread(new MyTask(i)); thread.start(); } System.out.printf("Factory stats:\n"); System.out.printf("%s\n",factory.getStas()); System.out.println("main thread end"); } }