1.CachedThreadPool
CachedThreadPool首先会按照需要创建足够多的线程来执行任务(Task)。随着程序执行的过程,有的线程执行完了任务,可以被重新循环使用时,才不再创建新的线程来执行任务。我们采用《Thinking In Java》中的例子来分析。
首先,任务定义如下(实现了Runnable接口,并且复写了run方法):
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
package net.jerryblog.concurrent;
public class LiftOff implements Runnable{
protected int countDown = 10 ; //Default
private static int taskCount = 0 ;
private final int id = taskCount++;
public LiftOff() {}
public LiftOff( int countDown) {
this .countDown = countDown;
}
public String status() {
return "#" + id + "(" +
(countDown > 0 ? countDown : "LiftOff!" ) + ") " ;
}
@Override public void run() {
while (countDown-- > 0 ) {
System.out.print(status());
Thread.yield();
}
}
} |
采用CachedThreadPool方式执行编写的客户端程序如下:
1
2
3
4
5
6
7
8
9
10
11
12
|
package net.jerryblog.concurrent;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class CachedThreadPool {
public static void main(String[] args) {
ExecutorService exec = Executors.newCachedThreadPool();
for ( int i = 0 ; i < 10 ; i++) {
exec.execute( new LiftOff());
}
exec.shutdown();
}
} |
上面的程序中,有10个任务,采用CachedThreadPool模式,exec没遇到一个LiftOff的对象(Task),就会创建一个线程来处理任务。现在假设遇到到第4个任务时,之前用于处理第一个任务的线程已经执行完成任务了,那么不会创建新的线程来处理任务,而是使用之前处理第一个任务的线程来处理这第4个任务。接着如果遇到第5个任务时,前面那些任务都还没有执行完,那么就会又新创建线程来执行第5个任务。否则,使用之前执行完任务的线程来处理新的任务。
2.FixedThreadPool
FixedThreadPool模式会使用一个优先固定数目的线程来处理若干数目的任务。规定数目的线程处理所有任务,一旦有线程处理完了任务就会被用来处理新的任务(如果有的话)。这种模式与上面的CachedThreadPool是不同的,CachedThreadPool模式下处理一定数量的任务的线程数目是不确定的。而FixedThreadPool模式下最多 的线程数目是一定的。
采用FixedThreadPool模式编写客户端程序如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
|
package net.jerryblog.concurrent;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class FixedThreadPool {
public static void main(String[] args) {
//三个线程来执行五个任务
ExecutorService exec = Executors.newFixedThreadPool( 3 );
for ( int i = 0 ; i < 5 ; i++) {
exec.execute( new LiftOff());
}
exec.shutdown();
}
} |
3.SingleThreadExecutor模式
SingleThreadExecutor模式只会创建一个线程。它和FixedThreadPool比较类似,不过线程数是一个。如果多个任务被提交给SingleThreadExecutor的话,那么这些任务会被保存在一个队列中,并且会按照任务提交的顺序,一个先执行完成再执行另外一个线程。
SingleThreadExecutor模式可以保证只有一个任务会被执行。这种特点可以被用来处理共享资源的问题而不需要考虑同步的问题。
SingleThreadExecutor模式编写的客户端程序如下:
1
2
3
4
5
6
7
8
9
10
11
|
package net.jerryblog.concurrent;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class SingleThreadExecutor {
public static void main(String[] args) {
ExecutorService exec = Executors.newSingleThreadExecutor();
for ( int i = 0 ; i < 2 ; i++) {
exec.execute( new LiftOff());
}
}
} |
这种模式下执行的结果如下:
1
2
|
# 0 ( 9 ) # 0 ( 8 ) # 0 ( 7 ) # 0 ( 6 ) # 0 ( 5 ) # 0 ( 4 ) # 0 ( 3 ) # 0 ( 2 ) # 0 ( 1 ) # 0 (LiftOff!)
# 1 ( 9 ) # 1 ( 8 ) # 1 ( 7 ) # 1 ( 6 ) # 1 ( 5 ) # 1 ( 4 ) # 1 ( 3 ) # 1 ( 2 ) # 1 ( 1 ) # 1 (LiftOff!)
|
第一个任务执行完了之后才开始执行第二个任务。