第9章 Java中的线程池 ThreadPoolExecutor

来源:互联网 发布:tensorflow feed 图像 编辑:程序博客网 时间:2024/06/03 16:43
1 线程池的实现原理

线程池的主要处理流程:

ThreadPoolExecutor 执行示意图:


ThreadPoolExecutor执行execute方法分下面4种情况。
1)如果当前运行的线程少于corePoolSize,则创建新线程来执行任务(注意,执行这一步骤需要获取全局锁)。
2)如果运行的线程等于或多于corePoolSize,则将任务加入BlockingQueue。
3)如果无法将任务加入BlockingQueue(队列已满),则创建新的线程来处理任务(注意,执行这一步骤需要获取全局锁)。
4)如果创建新线程将使当前运行的线程超出maximumPoolSize,任务将被拒绝,并调用
RejectedExecutionHandler.rejectedExecution()方法。

ThreadPoolExecutor采取上述步骤的总体设计思路,是为了在执行execute()方法时,尽可能地避免获取全局锁(那将会是一个严重的可伸缩瓶颈)。在ThreadPoolExecutor完成预热之后(当前运行的线程数大于等于corePoolSize),几乎所有的execute()方法调用都是执行步骤2,而步骤2不需要获取全局锁。

源码分析:
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
public void execute(Runnable command) {  
        if (command == null)  
            throw new NullPointerException();  
         
        int c = ctl.get();  
        //如果当前工作线程数量小于corePoolSize,直接执行任务
       if (workerCountOf(c) < corePoolSize) {  
            //新建一个core线程
            if (addWorker(command, true))  
                return;  
            c = ctl.get();  
        }  
       //判断目前线程的状态是不是RUNNING其他线程有可能调用了shutdown()或shutdownNow()方法,
       //关闭线程池,导致目前线程的状态不是RUNNING,
       //如果是Running,往workQueue添加一个元素,添加成功返回TRUE,
        if (isRunning(c) && workQueue.offer(command)) {  
            int recheck = ctl.get();  
            if (! isRunning(recheck) && remove(command))  
                reject(command);  
            //线程均被释放了,新建一个线程
            else if (workerCountOf(recheck) == 0)  
                addWorker(nullfalse);  
        }  
       // 阻塞队列满了,则尝试新建非core线程
        else if (!addWorker(command, false))  
            reject(command);  
    }  

2 线程池的使用

2.1 可以通过ThreadPoolExecutor来创建一个线程池
全参数构造方法:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
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.corePoolSize = corePoolSize;
        this.maximumPoolSize = maximumPoolSize;
        this.workQueue = workQueue;
        this.keepAliveTime = unit.toNanos(keepAliveTime);
        this.threadFactory = threadFactory;
        this.handler = handler;
    }
相关注释:
  • corePoolSize 是线程池的核心线程数,通常线程池会维持这个线程数
  • maximumPoolSize 是线程池所能维持的最大线程数
  • keepAliveTime 和 unit 则分别是超额(空闲)线程的空闲存活时间数和时间单位
  • workQueue 是提交任务到线程池的入队列
  • threadFactory 是线程池创建新线程的线程构造器
  • RejectedExecutionHandler(饱和策略) 这个策略默认情况下是AbortPolicy,表示无法处理
    新任务时抛出异常。Java线程池框架提供了以下4种策略。
    ·AbortPolicy:直接抛出异常。
    ·CallerRunsPolicy:只用调用者所在线程来运行任务。
    ·DiscardOldestPolicy:丢弃队列里最近的一个任务,并执行当前任务。
    ·DiscardPolicy:不处理,丢弃掉。
    当然,也可以根据应用场景需要来实现RejectedExecutionHandler接口自定义策略。如记录日志
    或持久化存储不能处理的任务,


2.2 向线程池提交任务

      可以使用两个方法向线程池提交任务,分别为execute()和submit()方法

execute()方法用于提交不需要返回值的任务
1
2
3
4
5
6
threadsPool.execute(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
}
});
submit()方法用于提交需要返回值的任务。线程池会返回一个future类型的对象,通过这个future对象可以判断任务是否执行成功,并且可以通过future的get()方法来获取返回值,get()方法会阻塞当前线程直到任务完成,而使用get(long timeout,TimeUnit unit)方法则会阻塞当前线程一段时间后立即返回,这时候有可能任务没有执行完。
1
2
3
4
5
6
7
8
9
10
11
Future<Object> future = executor.submit(harReturnValuetask);
try {
Object s = future.get();
catch (InterruptedException e) {
// 处理中断异常
catch (ExecutionException e) {
// 处理无法执行任务异常
finally {
// 关闭线程池
executor.shutdown();
}

2.3 关闭线程池

shutdown()和shutdowNow()
它们的原理是遍历线程池中的工作线程,然后逐个调用线程的interrupt方法来中断线程,所以无法响应中断的任务可能永远无法终止。但是它们存在一定的区别,shutdownNow首先将线程池的状态设置成STOP,然后尝试停止所有的正在执行或暂停任务的线程,并返回等待执行任务的列表,而shutdown只是将线程池的状态设置成SHUTDOWN状态,然后中断所有没有正在执行任务的线程。

只要调用了这两个关闭方法中的任意一个,isShutdown方法就会返回true。当所有的任务都已关闭后,才表示线程池关闭成功,这时调用isTerminaed方法会返回true


2.4 合理地配置线程池

        性质不同的任务可以用不同规模的线程池分开处理。CPU密集型任务应配置尽可能小的线程,如配置Ncpu+1个线程的线程池。由于IO密集型任务线程并不是一直在执行任务,则应配置尽可能多的线程,如2*Ncpu。混合型的任务,如果可以拆分,将其拆分成一个CPU密集型任务和一个IO密集型任务,只要这两个任务执行的时间相差不是太大,那么分解后执行的吞吐量将高于串行执行的吞吐量。如果这两个任务执行时间相差太大,则没必要进行分解。可以通过Runtime.getRuntime().availableProcessors()方法获得当前设备的CPU个数。
        优先级不同的任务可以使用优先级队列PriorityBlockingQueue来处理。它可以让优先级高的任务先执行。
        执行时间不同的任务可以交给不同规模的线程池来处理,或者可以使用优先级队列,让执行时间短的任务先执行。
        依赖数据库连接池的任务,因为线程提交SQL后需要等待数据库返回结果,等待的时间越长,则CPU空闲时间就越长,那么线程数应该设置得越大,这样才能更好地利用CPU。

      建议使用有界队列。有界队列能增加系统的稳定性和预警能力,可以根据需要设大一点儿,比如几千。

2.5 线程池的监控

        如果在系统中大量使用线程池,则有必要对线程池进行监控,方便在出现问题时,可以根据线程池的使用状况快速定位问题。可以通过线程池提供的参数进行监控,在监控线程池的时候可以使用以下属性。
        ·taskCount:线程池需要执行的任务数量。
        ·completedTaskCount:线程池在运行过程中已完成的任务数量,小于或等于taskCount。
        ·largestPoolSize:线程池里曾经创建过的最大线程数量。通过这个数据可以知道线程池是否曾经满过。如该数值等于                                      线程池的最大大小,则表示线程池曾经满过。
        ·getPoolSize:线程池的线程数量。如果线程池不销毁的话,线程池里的线程不会自动销毁,所以大小只增不减。
        ·getActiveCount:获取活动的线程数。
通过扩展线程池进行监控。可以通过继承线程池来自定义线程池,重写线程池的beforeExecute、afterExecute和terminated方法,也可以在任务执行前、执行后和线程池关闭前执行一些代码来进行监控。例如,监控任务的平均执行时间、最大执行时间和最小执行时间等。这几个方法在线程池里是空方法。


监控以及线程池使用案例如下:

线程池监控代码:
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
package com.tlk.chapter9;
 
import java.util.concurrent.ThreadPoolExecutor;
 
public class MyMonitorThread implements Runnable
{
    private ThreadPoolExecutor executor;
  
    private int seconds;
  
    private boolean run=true;
  
    public MyMonitorThread(ThreadPoolExecutor executor, int delay)
    {
        this.executor = executor;
        this.seconds=delay;
    }
  
    public void shutdown(){
        this.run=false;
    }
  
    @Override
    public void run()
    {
        while(run){
                System.out.println(
                    String.format("[monitor] [%d/%d] Active: %d, Completed: %d, Task: %d, isShutdown: %s, isTerminated: %s",
                        this.executor.getPoolSize(),
                        this.executor.getCorePoolSize(),
                        this.executor.getActiveCount(),
                        this.executor.getCompletedTaskCount(),
                        this.executor.getTaskCount(),
                        this.executor.isShutdown(),
                        this.executor.isTerminated()));
                try {
                    Thread.sleep(seconds*1000);
                catch (InterruptedException e) {
                    e.printStackTrace();
                }
        }
  
    }
}

执行execute方法
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
package com.tlk.chapter9;
 
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
 
public class ThreadPoolExecutorTest {
    public static void main(String[] args) {
        ThreadPoolExecutor executor = new ThreadPoolExecutor(510, 0L, TimeUnit.MILLISECONDS,
                new LinkedBlockingQueue<Runnable>(), Executors.defaultThreadFactory(), new ThreadPoolExecutor.AbortPolicy());
         
         MyMonitorThread monitor = new MyMonitorThread(executor, 3);
        Thread monitorThread = new Thread(monitor);
        monitorThread.start();
     
        for(int i=0; i<20; i++){
            executor.execute(new Runnable() {
                @Override
                public void run() {
                    try {
                        TimeUnit.SECONDS.sleep(6);
                    catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(Thread.currentThread().getName());
                }
            });
            try {
                TimeUnit.SECONDS.sleep(1);
            catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
         
        executor.shutdown();
        while(!executor.isTerminated()){
             
        }
        monitor.shutdown();
        System.out.println("所有线程都已执行完毕");
         
    }
}

执行submit方法
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
package com.tlk.chapter9;
 
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
 
public class ExecutorServiceSubmitTest {  
    public static void main(String[] args) {  
        ExecutorService executorService = Executors.newCachedThreadPool();  
        List<Future<String>> resultList = new ArrayList<Future<String>>();  
   
        // 创建10个任务并执行  
        for (int i = 0; i < 10; i++) {  
            // 使用ExecutorService执行Callable类型的任务,并将结果保存在future变量中  
            Future<String> future = executorService.submit(
                    new Callable<String>() {
                        @Override
                        public String call() throws Exception {
                            String xx = String.valueOf(Math.random());
                            System.out.println("xxxxxxx:" + xx);
                            return xx;
                        }
                    }
            );  
            // 将任务执行结果存储到List中  
            resultList.add(future);  
        }  
        executorService.shutdown();  
   
        // 遍历任务的结果  
        for (Future<String> fs : resultList) {  
            try {  
                System.out.println(fs.get()); // 打印各个线程(任务)执行的结果  
            catch (InterruptedException e) {  
                e.printStackTrace();  
            catch (ExecutionException e) {  
                executorService.shutdownNow();  
                e.printStackTrace();  
                return;  
            }  
        }  
    }  
}  
原创粉丝点击