创建固定大小的线程池的时候使用ThreadFactory
public static ExecutorService newFixedThreadPool( int nThreads, ThreadFactory threadFactory) { return new ThreadPoolExecutor(nThreads, nThreads, 0L, TimeUnit. MILLISECONDS, new LinkedBlockingQueue<Runnable>(), threadFactory); }ThreadFactory的作用:构造一个新 Thread。实现也可能初始化属性、名称、守护程序状态、ThreadGroup 等等。
在写demo的时候,我认为最麻烦的就是,设置循环中创建的线程的join方法。 在没有使用线程池的时候,在循环中调用这个方法都麻烦,要么抛出异常,要么就只有再循环一次来单独设置。 就这个场景而言,使用ThreadFactory来就很简单了。 ——————– 好把,我以为在工厂中,自己调用join方法能行。但是测试过了。视乎没有效果。 那就只能看下用法。场景用途我暂时也不知道了
示例如下:
/**
* Created by zhuqiang on 2015/8/25 0025.
*/
public class Client {
public static void main(String[] args) {
// ThreadPoolExecutor es = (ThreadPoolExecutor) Executors.newFixedThreadPool(3); //1 该注释代码。和下面为使用工厂的对比。
ThreadPoolExecutor es = (ThreadPoolExecutor) Executors.newFixedThreadPool(3, new ThreadFactory() {
@Override
public Thread newThread(Runnable r) {
Thread thread = new Thread(r);
thread.setName("xxxx" + thread.getId()); //对新创建的线程做一些操作
return thread;
}
});
for (int i = 0; i < 10 ; i++) {
es.execute(new Task(es,"task-"+i));
}
es.shutdown();
}
}
class Task implements Runnable{
private ThreadPoolExecutor es;
private String name;
public Task(ThreadPoolExecutor es, String name) {
this.es = es;
this.name = name;
}
@Override
public void run() {
try {
long timeout = (long) (Math.random() * 10);
TimeUnit.SECONDS.sleep(timeout);
System.out.println(Thread.currentThread().getName() + "...执行完成..task=" + name +" 耗时:" + timeout);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}