0%

前言

线程初学者杂记

线程池

ThreadPoolExecutor

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
/**
* Creates a new {@code ThreadPoolExecutor} with the given initial
* parameters.
*
* @param corePoolSize the number of threads to keep in the pool, even
* if they are idle, unless {@code allowCoreThreadTimeOut} is set
* @param maximumPoolSize the maximum number of threads to allow in the
* pool
* @param keepAliveTime when the number of threads is greater than
* the core, this is the maximum time that excess idle threads
* will wait for new tasks before terminating.
* @param unit the time unit for the {@code keepAliveTime} argument
* @param workQueue the queue to use for holding tasks before they are
* executed. This queue will hold only the {@code Runnable}
* tasks submitted by the {@code execute} method.
* @param threadFactory the factory to use when the executor
* creates a new thread
* @param handler the handler to use when execution is blocked
* because the thread bounds and queue capacities are reached
* @throws IllegalArgumentException if one of the following holds:<br>
* {@code corePoolSize < 0}<br>
* {@code keepAliveTime < 0}<br>
* {@code maximumPoolSize <= 0}<br>
* {@code maximumPoolSize < corePoolSize}
* @throws NullPointerException if {@code workQueue}
* or {@code threadFactory} or {@code handler} is null
*/
public ThreadPoolExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue<Runnable> workQueue,
ThreadFactory threadFactory,
RejectedExecutionHandler handler) {
}

分类

  • Executors.newFixedThreadPool(n) 核心线程数量为 n 的线程池,不超时。任务队列没有限制。
  • Executors.newCachedThreadPool() 非核心线程数量为无限大,超过 60 秒回收,队列队列中的任务会立即创建新线程进行处理。
  • Executors.newScheduledThreadPool(n) 核心线程数量固定为 n ,非核心线程数量没有限制,非核心线程闲置后会立即回收。用于执行定时任务和固定周期的重复任务。
  • Executors.newSingleThreadExecutor() 只有一个核心线程。所有任务都在同一个线程中按顺序执行。

这是一段漫长的岁月,一段特殊的岁月

阅读全文 »

类定义

C++ 类的声明和定义通常是分开在两个不同的文件中,分别是 .h 头文件 和 .cpp 文件

阅读全文 »