之前创建线程的话,基本上是使用new Thread(),或者是将任务提交到线程池执行。今天看了一下洁城浩的《图解java多线程设计模式》突然看到还可以使用ThreadFactory来创建一个线程,感觉挺新奇的,就写了一个Example类来跑一下 。
1 public class ThreadFactoryExample { 2 public static void main(String[] args) { 3 ThreadFactory factory = Executors.defaultThreadFactory(); 4 factory.newThread(new Task()).start(); 5 for (int i = 0; i < 10; i++) { 6 System.out.println("Hello"); 7 } 8 } 9 } 10 11 class Task implements Runnable { 12 13 @Override 14 public void run() { 15 for (int i = 0; i < 10; i++) { 16 System.out.println("Task"); 17 } 18 } 19 }
挺简单的使用方式。看了一下,Executors工具类返回的是DefaultThreadFactory类的实例,这个类的是一个Executors的内部类,代码很少,如下
1 static class DefaultThreadFactory implements ThreadFactory { 2 private static final AtomicInteger poolNumber = new AtomicInteger(1); 3 private final ThreadGroup group; 4 private final AtomicInteger threadNumber = new AtomicInteger(1); 5 private final String namePrefix; 6 7 DefaultThreadFactory() { 8 SecurityManager s = System.getSecurityManager(); 9 group = (s != null) ? s.getThreadGroup() : 10 Thread.currentThread().getThreadGroup(); 11 namePrefix = "pool-" + 12 poolNumber.getAndIncrement() + 13 "-thread-"; 14 } 15 16 public Thread newThread(Runnable r) { 17 Thread t = new Thread(group, r, 18 namePrefix + threadNumber.getAndIncrement(), 19 0); 20 if (t.isDaemon()) 21 t.setDaemon(false); 22 if (t.getPriority() != Thread.NORM_PRIORITY) 23 t.setPriority(Thread.NORM_PRIORITY); 24 return t; 25 } 26 }