• 线程池的作用
  1. 线程池可以有效控制系统内执行线程的数量;
  2. 根据系统的状况可以手动或自动调整执行线程的数量,让其他线程排队等候;
  3. 线程池可以有效减少线程创建和销毁的次数,使得线程可以复用,可以执行多任务。
  • JAVA中常用的线程池
  1. newSingleThreadExecutor()
    创建一个单线程的线程池,线程池中只有一个线程在工作(相当于单线程串行执行所有任务)。如果唯一的线程异常结束,将会创建一个新的线程来代替,同时任务按照队列顺序执行。
    方法解释:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
/**
* Executors.newSingleThreadExecutor()
* Creates an Executor that uses a single worker thread operating
* off an unbounded queue.
* 使用单操作线程创建一个没有限制队列的Executor
* (Note however that if this single
* thread terminates due to a failure during
* execution prior toshutdown, a new one will
* take its place if needed to execute
* subsequent tasks.)
* 但是请注意,如果该单线程由于在关机之前执行期间失败而终
* 止,则在执行后续任务时需要使用一个新线程。
* Tasks are guaranteed to execute
* sequentially, and no more than one task will
* be active at any given time.
* 确保任务按顺序执行,并且在任何给定时间都不会激活一项以上
* 的任务。
* Unlike the otherwise equivalent
* {@code newFixedThreadPool(1)} the returned
* executor is guaranteed not to be
* reconfigurable to use additional threads.
*与其他等效的{@code newFixedThreadPool(1)}不同,保
证返回的执行程序不可重新配置为使用其他线程。
* @return the newly created single-threaded Executor
*/
public static ExecutorService newSingleThreadExecutor() {
return new FinalizableDelegatedExecutorService
(new ThreadPoolExecutor(1, 1,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>()));
}
  1. newFixedThreadPool(int nThreads)

创建一个固定线程数量的线程池,每次提交的任务就创建一个线程,直到线程数量达到线程数量限制。其余多的任务进入等待队列,直到有空闲的线程。如果有线程异常结束,那么就会创建一个新的线程来代替它。
方法解释:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
/**
* Executors.newFixedThreadPool(int nThreads)
* Creates a thread pool that reuses a fixed
* number of threads operating off a shared
* unbounded queue.
* 创建一个线程池,该线程池重用在共享的无边界队列上运行的固
* 定数量的线程。
* Atany point, at most{@code nThreads} threads
* will be activeprocessing tasks.
* 无论何时,最多{@code nThreads}个线程都是活动处理任
* 务。
* If additional tasks are submitted when all
* threads are active,they will wait in the queue
* until a thread is available.
* 如果在所有线程都处于活动状态时提交了其他任务,则它们将
* 在队列中等待,直到某个线程可用为止。
* If any thread terminates due to a failure
* during execution prior to shutdown, a new one
* will take itsplace if needed to execute
* subsequent tasks.
* 如果在关闭之前执行过程中由于执行失败导致任何线程终止,则
* 在执行后续任务时将替换一个新线程。
* The threads in thepool will exist
* until it is explicitly {@link
* ExecutorService#shutdown shutdown}.
*这个线程在池中将一直存在知道明确的shutdown。
* @param nThreads the number of threads in the
* pool
* @return the newly created thread pool
* @throws IllegalArgumentException if {@code
* nThreads <= 0}
*/
public static ExecutorService newFixedThreadPool(int nThreads) {
return new ThreadPoolExecutor(nThreads, nThreads,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>());
}
  1. newCachedThreadPool()

创意一个可以缓冲的线程池,如果当前线程数超出了执行任务的数量,那么在等待60s无新任务的情况下结束掉。当任务数量增加的情况下,线程池又会自动增加线程数量。线程池对线程的数量没有做限制。
方法解释:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
/**
* Executors.newCachedThreadPool()
* Creates a thread pool that creates new threads
* as needed, but
* will reuse previously constructed threads when
* they are available.
* 创建一个线程池,该线程池根据需要创建新线程,但是将在先前
* 构造的线程可用时重用它们。
* These pools will typically improve the
* performance of programs that execute many
* short-lived asynchronous tasks.
* 这些池通常将提高执行许多短期异步任务的程序的性能。
* Calls to {@code execute} will reuse previously
* constructed threads if available.
* 调用{@code execute}将重用之前构造的可重用的线程
* If no existing thread is available, a new
* thread will be created and added to the pool.
* 如果不存在可重用的线程,那么一个新的线程将会被创建并添加
* 到池中。
* Threads that have not been used for sixty
* seconds are terminated and removed from the
* cache.
* 六十秒内未使用的线程将终止并从缓存中删除。
* Thus, a pool that remains idle for
* long enough will not consume any resources.
* 因此,一个保持足够长的池也不会消耗任何资源。
* Note that pools with similar properties but
* different details (for example, timeout
* parameters) may be created using {@link
* ThreadPoolExecutor} constructors.
*请注意,可以使用{@link ThreadPoolExecutor}构造函数创
建具有相似属性但不同详细信息(例如,超时参数)的池。
* @return the newly created thread pool
*/
public static ExecutorService newCachedThreadPool() {
return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
60L, TimeUnit.SECONDS,
new SynchronousQueue<Runnable>());
}