每当线程池需要创建一个线程时,都是通过线程工厂方法来完善的。默认的线程工厂方法将创建一个新的、非守护的线程,并且不包含特殊的配置信息,通过指定一个线程工厂方法,可以线程池的配置信息。
需要定制线程工厂方法的情景 :
线程工厂只有一个抽象方法:
public interface ThreadFactory {
/**
* Constructs a new {@code Thread}. Implementations may also initialize
* priority, name, daemon status, {@code ThreadGroup}, etc.
*
* @param r a runnable to be executed by new thread instance
* @return constructed thread, or {@code null} if the request to
* create a thread is rejected
*/
Thread newThread(Runnable r);
}
上面的功能都在Thread类里面。
在使用ThreadPoolExecutor的构造函数之后,仍然可以通过Set方法来配置线程池
ExecutorService exec = Executors.newCachedThreadPool();
if (exec instanceof ThreadPoolExecutor) {
((ThreadPoolExecutor) exec).setCorePoolSize(10);
} else
throw new AssertionError("bad assuption");如果我们不想创建出来的线程池被再次修改,可以用这个方法把它包装起来,变成“final"类型
Executors.unconfigurableExecutorService(executor);
ThreadPoolExecutor是可扩展的,比如我们可以为线程添加统计信息,重载BeforeExecute和AfterExecute方法用于计时等操作
其实很简单,对循环内的每个执行都用线程池来解决就好了
普通的串行递归
void processSequentially(List<Element> element) {
for (Element e : element) {
process(e);
}
}递归并行化
void processInParallel(Executor exec, List<Element> element) {
for (final Element e : element) {
exec.execute(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
process(e);
}
});
}
}
原文地址:http://blog.csdn.net/lingchixin/article/details/39120015