前边我们讲述了:Java多线程高并发之基础概念篇、Java多线程高并发之详解JUC同步工具
分别从以下几个方面了解线程的概念及如何使用:
1、线程是什么?为什么需要多线程?Java如何实现多线程?
2、Java对多线程的基础操作:线程的状态扭转,线程的创建、终止、中断、等待和通知、挂起和执行、等待结束和谦让,synchronized实现原理及volatile和synchronized关键字在多线程环境下的作用及如何使用。
3、多线程的协作——同步控制工具:
- ReentrantLock可重入锁:什么情况下可重入及与synchronized的区别;
- CountDownLatch倒计时器:对线程的统一汇总;
- CyclicBarrier循环栅栏:对线程进行循环统一汇总;
- Phaser阶段:可以将一个连续的执行过程分成固定阶段,可以控制栅栏的个数和等待线程的个数;
- ReadWriteLock读写锁:读写分开执行,提高性能;
- Semahore信号灯:限流,允许多个线程同时执行;
- Exchanger交换器:支持线程之间交换数据;
- LockSupport线程阻塞工具:可以让线程在任意位置阻塞;
- Condition:条件实现等待通知;
然而面对这么多的线程操作,我们如何管理这些线程呢?接下来我们本文需要介绍的ThreadPool就派上用场了;我们从以下几个方面了解Java的线程池
一、什么是线程池
二、JDK中的线程池
三、线程池的实现原理
四、线程池的使用
五、分而治之:ForkJoinPool
一、什么是线程池
想必大家对数据库连接池并不陌生,其实线程池和数据库连接池是一样的原理:
线程池中维护着需要执行的线程队列和任务队列;
为了避免系统频繁的创建和销毁线程带来的性能消耗,可以让线程得到很好的复用。当需要使用线程时从线程池取(创建),当用完时归还线程池(销毁)从而最大化地使用系统资源。
二、JDK中的线程池
我们可以通过查看java.util.concurrent包下的对应类的源码对线程池进行各种控制的类关系图(Executor框架)进行解读。通过Executors类的方法可以看出:
ExecutorService newFixedThreadPool(int nThreads)可以创建固定数量的线程池;
ExecutorService newSingleThreadExecutor()可以创建只有一个线程的线程池;
ExecutorService newCachedThreadPool() 可以返回一个根据实际情况调整线程数量的线程池;
ScheduledExecutorService newSingleThreadScheduledExecutor()可以返回一个可以执行定时任务线程的线程池;
ScheduledExecutorService newScheduledThreadPool(int corePoolSize)可以返回指定数量可以执行定时任务的线程池。
三、线程池的实现原理
通过看JDK源码可以知道上边五种类型的线程池创建无论哪种最后都是ThreadPoolExecutor类的封装,我们来看下ThreadPoolExecutor最原始的构造函数,和调度execute源码:
/**
* 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) {
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;
}
public void execute(Runnable command) {
if (command == null)
throw new NullPointerException();
/*
* Proceed in 3 steps:
*
* 1. If fewer than corePoolSize threads are running, try to
* start a new thread with the given command as its first
* task. The call to addWorker atomically checks runState and
* workerCount, and so prevents false alarms that would add
* threads when it shouldn't, by returning false.
*
* 2. If a task can be successfully queued, then we still need
* to double-check whether we should have added a thread
* (because existing ones died since last checking) or that
* the pool shut down since entry into this method. So we
* recheck state and if necessary roll back the enqueuing if
* stopped, or start a new thread if there are none.
*
* 3. If we cannot queue task, then we try to add a new
* thread. If it fails, we know we are shut down or saturated
* and so reject the task.
*/
int c = ctl.get();
if (workerCountOf(c) < corePoolSize) {
if (addWorker(command, true))
return;
c = ctl.get();
}
if (isRunning(c) && workQueue.offer(command)) {
int recheck = ctl.get();
if (! isRunning(recheck) && remove(command))
reject(command);
else if (workerCountOf(recheck) == 0)
addWorker(null, false);
}
else if (!addWorker(command, false))
reject(command);
}
}
ThreadPoolExecutor 参数详解:
第1个参数:corePoolSize核心线程数
第2个参数:maximumPoolSize最大线程数
第3个参数:keepAliveTime线程长时间不干活,多少时间归还给OS(超过corePoolSize个多余线程的存活时间)
第4个参数:TimeUnit: keepAliveTime的时间单位
第5个参数:BlockingQueue各种队列及任务个数(ArrayBlockingQueu(4)4个任务的阻塞队列)
当任务被提交但尚未被执行的任务队列,是一个BlockingQueue接口的对象,只存放Runnable对象。根据队列功能分类,看下JDK提供的几种BlockingQueue:
work queue class name | 说明 |
---|---|
SynchronousQueue | 直接提交队列:没有容量,每一个插入操作都要等待一个相应的删除操作。通常使用需要将maximumPoolSize的值设置很大,否则很容易触发拒绝策略。 |
ArrayBlockingQueue | 有界的任务队列:任务大小通过入参 int capacity决定,当填满队列后才会创建大于corePoolSize的线程。 |
LinkedBlockingQueue | 无界的任务队列:线程个数最大为corePoolSize,如果任务过多,则不断扩充队列,知道内存资源耗尽。 |
PriorityBlockingQueue | 优先任务队列:是一个无界的特殊队列,可以控制任务执行的先后顺序,而上边几个都是先进先出的策略。 |
第6个参数:ThreadFactory 线程生产工厂(设置线程名称-便于出错时回溯,线程优先级,是否为守护线程,)
第7个参数:RejectedExecutionHandler 线程池满,而且线程都忙,执行拒绝粗略。(粗略可自定义,jdk默认提供4种);
策略名称 | 说明 |
---|---|
AbortPolicy | 抛异常:该策略会直接抛出异常,阻止系统正常 工作。线程池默认为此。 |
CallerRunsPolicy | 调用者处理任务:只要线程池未关闭,该策略直接在调用者线程中,运行当前被丢弃的任务。 |
DiscardOledestPolicy | 扔掉排队时间最久的:该策略将丢弃最老的一个请求,也就是即将被执行的一个任务,并尝试重新提交当前任务 |
DiscardPolicy | 扔掉,不抛异常:该策略默默地丢弃无法处理的任务,不予任务处理。 |
execute三步:
1,创建线程直到corePoolSize;
2,加入任务队列;
3,如果还是执行不过来,则执行拒绝策略
四、线程池的使用
public class ThreadPoolDemo {
static class Task implements Runnable {
private int i;
public Task(int i) {
this.i = i;
}
@Override
public void run() {
System.out.println(Thread.currentThread().getName() + " Task " + i);
try {
System.in.read();
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public String toString() {
return "Task{" +
"i=" + i +
'}';
}
}
public static void main(String[] args) {
ThreadPoolExecutor tpe = new ThreadPoolExecutor(2, 4,
60, TimeUnit.SECONDS,
new ArrayBlockingQueue<Runnable>(4),
Executors.defaultThreadFactory(),
new ThreadPoolExecutor.CallerRunsPolicy());
for (int i = 0; i < 8; i++) {
tpe.execute(new Task(i));
}
System.out.println(tpe.getQueue());
tpe.execute(new Task(100));
System.out.println(tpe.getQueue());
tpe.shutdown();
}
}
public class RejectThreadPoolDemo {
public static class MyTask implements Runnable{
public void run() {
System.out.println(System.currentTimeMillis() + "Thread Name:" + Thread.currentThread().getName());
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
FixThreadPoolDemo.MyTask myTask = new FixThreadPoolDemo.MyTask();
ExecutorService es = new ThreadPoolExecutor(5, 5, 0L, TimeUnit.MILLISECONDS, new ArrayBlockingQueue<Runnable>(10), Executors.defaultThreadFactory(), new RejectedExecutionHandler() {
public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
System.out.println(r.toString() + "is discard");
}
});
for (int i = 0; i < 20 ; i++) {
es.submit(myTask);
}
}
}
五、分而治之:ForkJoinPool
ForkJoin是由JDK1.7后提供多线并发处理框架。ForkJoin的框架的基本思想是分而治之。
什么是分而治之?
分而治之就是将一个复杂的计算,按照设定的阈值进行分解成多个计算,然后将各个计算结果进行汇总。相应的ForkJoin将复杂的计算当做一个任务。而分解的多个计算则是当做一个子任务。
- 分解汇总的任务
- 用很少的线程可以执行很多的任务(子任务)TPE做不到先执行子任务
- 场景:CPU密集型
ForkJoin的使用:
ForkJoin提供RecursiveTask和RecursiveAction实现方式;
RecursiveAction与RecursiveTask区别在与RecursiveTask是有返回结果而RecursiveAction是没有返回结果。
下面通过一个简单示例理解:
public class ForkJoinThreadPoolDemo extends RecursiveTask<Long> {
private static final int THRESHOLD = 10000;
private long start;
private long end;
public ForkJoinThreadPoolDemo(long start, long end) {
this.start = start;
this.end = end;
}
@Override
protected Long compute() {
long sum = 0;
boolean canCompute = (end - start) < THRESHOLD;
if (canCompute) {
for (long i = start; i < end; i++) {
sum += i;
}
} else {
//分成100份进行处理
long step = (start + end) / 50;
ArrayList<ForkJoinThreadPoolDemo> subTasks = new ArrayList<ForkJoinThreadPoolDemo>();
long pos = start;
for (int i = 0; i < 50; i++) {
long lastOne = pos + step;
if (lastOne > end) {
lastOne = end;
}
ForkJoinThreadPoolDemo subTask = new ForkJoinThreadPoolDemo(pos, lastOne);
pos += step;
subTasks.add(subTask);
subTask.fork();
}
for (ForkJoinThreadPoolDemo t : subTasks) {
sum += t.join();
}
}
return sum;
}
public static void main(String[] args) {
ForkJoinPool forkJoinPool = new ForkJoinPool();
ForkJoinThreadPoolDemo task = new ForkJoinThreadPoolDemo(0, 20000);
ForkJoinTask<Long> result = forkJoinPool.submit(task);
try {
long res = result.get();
System.out.println("结果" + res); //结果199990000
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
}
ForkJoin工作窃取(work-stealing)
为什么ForkJoin会存在工作窃取呢?
因为我们将任务进行分解成多个子任务的时候。每个子任务的处理时间都不一样。例如分别有子任务A\B。如果子任务A的1ms的时候已经执行,子任务B还在执行。那么如果我们子任务A的线程等待子任务B完毕后在进行汇总,那么子任务A线程就会在浪费执行时间,最终的执行时间就以最耗时的子任务为准。而如果我们的子任务A执行完毕后,处理子任务B的任务,并且执行完毕后将任务归还给子任务B。这样就可以提高执行效率。而这种就是工作窃取。
ForJoin需要注意的点
使用ForkJoin将相同的计算任务通过多线程的进行执行。从而能提高数据的计算速度。在google的中的大数据处理框架mapreduce就通过类似ForkJoin的思想。通过多线程提高大数据的处理。但是我们需要注意:
- 使用这种多线程带来的数据共享问题,在处理结果的合并的时候如果涉及到数据共享的问题,我们尽可能使用JDK为我们提供的并发容器。
- 在使用JVM的时候我们要考虑OOM的问题,如果我们的任务处理时间非常耗时,并且处理的数据非常大的时候。会造成OOM。
- ForkJoin也是通过多线程的方式进行处理任务。那么我们不得不考虑是否应该使用ForkJoin。因为当数据量不是特别大的时候,我们没有必要使用ForkJoin。因为多线程会涉及到上下文的切换。所以数据量不大的时候使用串行比使用多线程快。