常用的线程池

Java定义了Executor接口并在该接口中定义了execute()用于执行一个线程任务,然后通过ExecutorService实现Executor接口并指向具体线程操作。ExecutorService接口有多个实现类可用于创建不同的线程池。

名称 说明
newWorkStealingPool 可缓存的线程池
newFixedThreadPool 固定大小的线程池
newScheduledThreadPool 可做任务调度的线程池
newSingleThreadExecutor 单个线程的线程池
newWorkStealingPool 足够大小的线程池,JDK1.8新增

newWorkStealingPool

1
2
3
4
5
public static ExecutorService newCachedThreadPool() {
return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
60L, TimeUnit.SECONDS,
new SynchronousQueue<Runnable>());
}

newWorkStealingPool用于创建一个缓存线程池。之所以叫缓存线程池,是因为它创建新线程时如果有可重用的线程,则重用他们,否则重新创建一个新的线程并将其添加到线程池中。对于执行时间很短的任务而言newWorkStealingPool线程池能很大程度的重用线程进而提高系统性能。

1
ExecutorService cachedThreadPool = Exectuors.newCachedThreadPool();

newFixedThreadPool

1
2
3
4
5
6
public static ExecutorService newFixedThreadPool(int nThreads, ThreadFactory threadFactory) {
return new ThreadPoolExecutor(nThreads, nThreads,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>(),
threadFactory);
}

newFixedThreadPool用于创建一个固定线程数量的线程池,并将线程资源存放在队列中循环使用。在newFixedThreadPool线程池中,若处于活动状态的线程数量大于等于核心线程池的数量,则新提交的任务将在阻塞队列中排队,直到有可用的线程资源,具体的创建方式如下:

1
ExecutorService fixedThreadPool  = Executors.newFixedThreadPool(5);

newScheduledThreadPool

1
2
3
4
public static ScheduledExecutorService newScheduledThreadPool(
int corePoolSize, ThreadFactory threadFactory) {
return new ScheduledThreadPoolExecutor(corePoolSize, threadFactory);
}

newScheduledThreadPool创建了一个可定时调度的线程池,可设置在给定的延迟时间后执行或者定期执行某个线程任务:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(3);
// 创建一个延迟3秒的执行线程
scheduledExecutorService.schedule(new Runnable(){
@Override
public void run() {
System.out.println("delay 3 seconds execu.");
}
}, 3, TimeUnit.SECONDS);
// 创建一个延迟1秒执行且每3秒执行一次的线程
scheduledExecutorService.scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
System.out.println("delay 1 seconds, repeat execute every 3 seconds");
}
}, 1, 3, TimeUnit.SECONDS);

newSingleThreadExecutor

1
2
3
4
5
6
public static ExecutorService newSingleThreadExecutor() {
return new FinalizableDelegatedExecutorService
(new ThreadPoolExecutor(1, 1,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>()));
}

newSingleThreadExecutor线程池会保证永远有且只有一个可用的线程,在该线程停止或发生异常时,newSingleThreadExecutor线程池会启动一个新的线程来代替该线程继续执行任务:

1
ExecutorService singleThread = Executors.newSingleThreadExecutor();

newWorkStealingPool

1
2
3
4
5
6
public static ExecutorService newWorkStealingPool(int parallelism) {
return new ForkJoinPool
(parallelism,
ForkJoinPool.defaultForkJoinWorkerThreadFactory,
null, true);
}

newWorkStealingPool创建持有足够线程的线程池来达到快速运算的目的,在内部通过使用多个队列来减少各个线程调度产生的竞争。

1
ExecutorService workStealing = Executors.newWorkStealingPool();