0%

Windows版本

版本说明

  1. 操作系统版本:Window10 X64,其他操作系统类似
  2. JDK版本:jdk1.8.0_192,安装后目录:C:\Program Files\Java\jdk1.8.0_192
阅读全文 »

newCachedThreadPool

创建一个可根据需要创建新线程的线程池,但是在以前构造的线程可用时将重用它们。对于执行很多短期异步任务的程序而言,这些线程池通常可提高程序性能。调用 execute 将重用以前构造的线程(如果线程可用)。如果现有线程没有可用的,则创建一个新线程并添加到池中。终止并从缓存中移除那些已有 60 秒钟未被使用的线程。创建一个可缓存线程池,如果线程池长度超过处理需要,可灵活回收空闲线程,若无可回收,则新建线程。因此,长时间保持空闲的线程池不会使用任何资源。

阅读全文 »

Executor

为了方便并发执行任务,出现了一种专门用来执行任务的实现,也就是Executor
由此,任务提交者不需要再创建管理线程,使用更方便,也减少了开销。Java 里面线程池的顶级接口是 Executor,但是严格意义上讲 Executor 并不是一个线程池,而只是一个执行线程的工具。真正的线程池接口是 ExecutorService。Executor定义规范。

阅读全文 »

使用线程池可以有以下优点:

  1. 降低资源消耗。通过重复利用已创建的线程降低线程创建和销毁造成的消耗。
  2. 提高响应速度。当任务到达时,任务可以不需要等到线程创建就能立即执行。
  3. 提高线程的可管理性。线程是稀缺资源,如果无限制地创建,不仅会消耗系统资源,还会降低系统的稳定性,使用线程池可以进行统一分配、调优和监控。
阅读全文 »

构建函数

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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
/**
* 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
* -- 当提交一个任务到线程池时,线程池会创建一个线程来执行任务,
* -- 即使其他空闲的基本线程能够执行新任务也会创建线程,
* -- 等到需要执行的任务数大于线程池基本大小时就不再创建。
* -- 调用prestartAllCoreThreads()后,线程池会提前创建并启动所有基本线程。
* @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
* -- 天(DAYS)、小时(HOURS)、分钟(MINUTES)、毫秒(MILLISECONDS)、
* -- 微秒(MICROSECONDS,千分之一毫秒)和纳秒(NANOSECONDS,千分之一微秒)
* @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.
* -- 用于保存等待执行的任务的阻塞队列
* -- ❑ ArrayBlockingQueue:基于数组结构的有界阻塞队列,排序规则:FIFO
* -- ❑ LinkedBlockingQueue:基于链表结构的阻塞队列,排序规则:FIFO,
吞吐量通常要高于ArrayBlockingQueue。
Executors.newFixedThreadPool()使用了这个队列。
* -- ❑ SynchronousQueue:一个不存储元素的阻塞队列(读写交换执行,否则会阻塞。)
吞吐量通常要高于Linked-BlockingQueue,
Executors.newCachedThreadPool使用了这个队列。
* -- ❑ PriorityBlockingQueue:一个具有优先级的无限阻塞队列。
* @param threadFactory the factory to use when the executor
* creates a new thread
* -- 设置创建线程的工厂,可以通过线程工厂给每个创建出来的线程设置更有意义的名字。
* -- 使用开源框架guava提供的ThreadFactoryBuilder
可以快速给线程池里的线程设置有意义的名字
* @param handler the handler to use when execution is blocked
* because the thread bounds and queue capacities are reached
* -- 当队列和线程池都满了(饱和状态),那么必须采取一种策略处理提交的新任务。
* -- 这个策略默认情况下是AbortPolicy,表示无法处理新任务时抛出异常
* -- ❑ AbortPolicy:直接抛出异常。
* -- ❑ CallerRunsPolicy:只用调用者所在线程来运行任务。
* -- ❑ DiscardOldestPolicy:丢弃队列里最近的一个任务,并执行当前任务。
* -- ❑ DiscardPolicy:不处理,丢弃掉。
* -- 实现RejectedExecutionHandler接口自定义策略
* @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) {
if (corePoolSize < 0 ||
maximumPoolSize <= 0 ||
maximumPoolSize < corePoolSize ||
keepAliveTime < 0)
throw new IllegalArgumentException();
if (workQueue == null || threadFactory == null || handler == null)
throw new NullPointerException();
this.acc = System.getSecurityManager() == null ?
null :
AccessController.getContext();
this.corePoolSize = corePoolSize;
this.maximumPoolSize = maximumPoolSize;
this.workQueue = workQueue;
this.keepAliveTime = unit.toNanos(keepAliveTime);
this.threadFactory = threadFactory;
this.handler = handler;
}
阅读全文 »

概述

API描述

1
2
3
4
5
6
* This class provides thread-local variables.  These variables differ from
* their normal counterparts in that each thread that accesses one (via its
* {@code get} or {@code set} method) has its own, independently initialized
* copy of the variable. {@code ThreadLocal} instances are typically private
* static fields in classes that wish to associate state with a thread (e.g.,
* a user ID or Transaction ID).

ThreadLocal提供一种线程本地变量。这种变量是一种副本的概念,在多线程环境下访问(get、set)能够保证各个线程间的变量互相隔离。ThreadLocal通常定义为了private static,用来关联线程和线程上下文(比如userId或事物ID)。ThreadLocal 的作用是提供线程内的局部变量,这种变量在线程的生命周期内起作用,减少同一个线程内多个函数或者组件之间一些公共变量的传递的复杂度。

阅读全文 »