标签:style blog color 使用 io strong for ar 问题
ThreadPoolExecutor线程池创建方法有两种:
1、Executors提供了常用线程池的工厂方法;
2、通过ThreadPoolExecutor构造方法创建
一般使用Executors提供的默认线程池,当默认的执行策略不满足需求,那么可以通过ThreadPoolExecutor的构造函数来实例化一个对象,并根据自己的需求来定制,下面是ThreadPoolExecutor通用的构造函数:
1 public ThreadPoolExecutor(int corePoolSize, 2 int maximumPoolSize, 3 long keepAliveTime, 4 TimeUnit unit, 5 BlockingQueue<Runnable> workQueue 6 ThreadFactory threadFactory, 7 RejectedExecutionHandler handler) { 8 ... 9 }
1 public interface ThreadFactory { 2 Thread newThread(Runnable r); 3 }
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 }
一般我们需要一个特定的线程池的名字,从而可以在错误日志信息中区分来自不同线程池的线程,就需要自己实现ThreadFactory接口,定制newThread方法。
标签:style blog color 使用 io strong for ar 问题
原文地址:http://www.cnblogs.com/peiyuc/p/3933422.html