标签:
An object that creates new threads on demand. Using thread factories removes hardwiring of calls tonew Thread
, enabling applications to use special thread subclasses, priorities, etc.
The simplest implementation of this interface is just:
class SimpleThreadFactory implements ThreadFactory { public Thread newThread(Runnable r) { return new Thread(r); } }
The
Executors.defaultThreadFactory
method provides a more useful simple implementation, that sets the created thread context to known values before returning it. /** * The default thread factory */ static class DefaultThreadFactory implements ThreadFactory { static final AtomicInteger poolNumber = new AtomicInteger(1); final ThreadGroup group; final AtomicInteger threadNumber = new AtomicInteger(1); 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; } }
package com.test; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.ThreadFactory; class Task implements Runnable{ int taskId; public Task(int taskId) { this.taskId=taskId; } @Override public void run() { System.out.println(Thread.currentThread().getName()+"--taskId: "+taskId); } } class DaemonThreadFactory implements ThreadFactory { @Override public Thread newThread(Runnable r) { Thread t=new Thread(r); t.setDaemon(true); return t; } } public class ThreadFactoryTest { public static void main(String[] args) { ExecutorService exec=Executors.newFixedThreadPool(3,new DaemonThreadFactory()); for(int i=0;i<3;i++) { exec.submit(new Task(i)); } exec.shutdown(); } }
标签:
原文地址:http://www.cnblogs.com/davygeek/p/5625572.html