Executor和线程池之我的理解

以前写线程,一般new一个Thread或者实现Runnable接口,jdk1.5之后引入了Executor框架,这个框架可以易于我们对线程的管理,复用线程,节约开销等等,Executor有一个很重要的子类,ExecutorService,也是一个接口,这才是我们经常要用的类,线程池ThreadPoolExecutor的父类实现了ExecutorService这个接口,常用的四个线程池,newCachedThreadPool,newFixedThreadPool(5),newSingleThreadExecutor,newScheduledThreadPool,
这四种线程池看源码都是利用ThreadPoolExecutor类来实现的,我们看先看看这个类的构造函数,然后解释下各个参数是什么意思

public ThreadPoolExecutor(int corePoolSize,
                              int maximumPoolSize,
                              long keepAliveTime,
                              TimeUnit unit,
                              BlockingQueue<Runnable> workQueue,
                              ThreadFactory threadFactory,
                              RejectedExecutionHandler handler) {

corePoolSize是线程池的核心线程数
maximumPoolSize线程池中的最大线程数
keepAliveTime 线程池中空闲线程所成持续的最长时间
unit keepAliveTime 的单位
workQueue 缓冲队列
threadFactory 线程工程模型
handler 如果缓冲队列已满,当前线程的线程数大于maximumPoolSize,那么交给handler处理
当我们调用excute想添加一个线程任务到线程池的时候,基本的规则如下:
1 如果线程池中的线程数量少于corePoolSize,即使线程池中有空闲线程,也会创建一个新的线程来执行新添加的任务。
2 如果线程池中的线程数量大于等于corePoolSize,并且线程池中没有空闲线程,缓冲队列workQueue未满,则将新添加的任务放到workQueue中,线程池中有线程空闲出来后依次将缓冲队列中的任务交付给空闲的线程执行
3 如果线程池中的线程数量大于等于corePoolSize,并且缓冲队列满了,那么看线程池中的线程数量是否小于maximumPoolSize,如果是,立刻创建一个新的线程来执行任务。
4 如果缓冲队列满了,线程池中的线程数也大于等于maximumPoolSize,那么交给handler处理,有4种处理方式,直接看源码:

 public static class CallerRunsPolicy implements RejectedExecutionHandler {
        /**
         * Creates a {@code CallerRunsPolicy}.
         */
        public CallerRunsPolicy() { }

        /**
         * Executes task r in the caller's thread, unless the executor
         * has been shut down, in which case the task is discarded.
         *
         * @param r the runnable task requested to be executed
         * @param e the executor attempting to execute this task
         */
        public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
            if (!e.isShutdown()) {
                r.run();
            }
        }
    }

    /**
     * A handler for rejected tasks that throws a
     * {@code RejectedExecutionException}.
     */
    public static class AbortPolicy implements RejectedExecutionHandler {
        /**
         * Creates an {@code AbortPolicy}.
         */
        public AbortPolicy() { }

        /**
         * Always throws RejectedExecutionException.
         *
         * @param r the runnable task requested to be executed
         * @param e the executor attempting to execute this task
         * @throws RejectedExecutionException always
         */
        public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
            throw new RejectedExecutionException("Task " + r.toString() +
                                                 " rejected from " +
                                                 e.toString());
        }
    }

    /**
     * A handler for rejected tasks that silently discards the
     * rejected task.
     */
    public static class DiscardPolicy implements RejectedExecutionHandler {
        /**
         * Creates a {@code DiscardPolicy}.
         */
        public DiscardPolicy() { }

        /**
         * Does nothing, which has the effect of discarding task r.
         *
         * @param r the runnable task requested to be executed
         * @param e the executor attempting to execute this task
         */
        public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
        }
    }

    /**
     * A handler for rejected tasks that discards the oldest unhandled
     * request and then retries {@code execute}, unless the executor
     * is shut down, in which case the task is discarded.
     */
    public static class DiscardOldestPolicy implements RejectedExecutionHandler {
        /**
         * Creates a {@code DiscardOldestPolicy} for the given executor.
         */
        public DiscardOldestPolicy() { }

        /**
         * Obtains and ignores the next task that the executor
         * would otherwise execute, if one is immediately available,
         * and then retries execution of task r, unless the executor
         * is shut down, in which case task r is instead discarded.
         *
         * @param r the runnable task requested to be executed
         * @param e the executor attempting to execute this task
         */
        public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
            if (!e.isShutdown()) {
                e.getQueue().poll();
                e.execute(r);
            }
        }
    }

1 CallerRunsPolicy 这个策略显然不想放弃执行任务。但是由于池中已经没有任何资源了,那么就直接使用调用该execute的线程本身来执行
2 AbortPolicy 这种策略会抛出异常
3 DiscardPolicy这种跟AbortPolicy类似,但不会抛出异常
4 DiscardOldestPolicy 这种会删除缓冲队列头部的任务,然后再次试图执行。

接下来再讲解一下很重要的缓冲队列的一些点:
排队有三种通用策略:
1 直接提交。工作队列的默认选项是 SynchronousQueue,它将任务直接提交给线程而不保持它们。在此,如果不存在可用于立即运行任务的线程,则试图把任务加入队列将失败,因此会构造一个新的线程。此策略可以避免在处理可能具有内部依赖性的请求集时出现锁。直接提交通常要求无界 maximumPoolSizes 以避免拒绝新提交的任务。当命令以超过队列所能处理的平均数连续到达时,此策略允许无界线程具有增长的可能性。
2 无界队列。使用无界队列(例如,不具有预定义容量的 LinkedBlockingQueue)将导致在所有 corePoolSize 线程都忙时新任务在队列中等待。这样,创建的线程就不会超过 corePoolSize。(因此,maximumPoolSize 的值也就无效了。)当每个任务完全独立于其他任务,即任务执行互不影响时,适合于使用无界队列;例如,在 Web 页服务器中。这种排队可用于处理瞬态突发请求,当命令以超过队列所能处理的平均数连续到达时,此策略允许无界线程具有增长的可能性。
3 有界队列。当使用有限的 maximumPoolSizes 时,有界队列(如 ArrayBlockingQueue)有助于防止资源耗尽,但是可能较难调整和控制。队列大小和最大池大小可能需要相互折衷:使用大型队列和小型池可以最大限度地降低 CPU 使用率、操作系统资源和上下文切换开销,但是可能导致人工降低吞吐量。如果任务频繁阻塞(例如,如果它们是 I/O 边界),则系统可能为超过您许可的更多线程安排时间。使用小型队列通常要求较大的池大小,CPU 使用率较高,但是可能遇到不可接受的调度开销,这样也会降低吞吐量。

下面来看看线程池的常规用法(一个一个的说):
一 newSingleThreadExecutor

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ExecutorTest {
    public static void main(String[] args) {
        ExecutorService pool = Executors.newSingleThreadExecutor();
//      ExecutorService executorService2 = Executors.newCachedThreadPool();
//      ExecutorService executorService3 = Executors.newSingleThreadExecutor();
//      ExecutorService executorService4 = Executors.newScheduledThreadPool(5);
        Thread t1 = new MyThread();
        Thread t2 = new MyThread();
        Thread t3 = new MyThread();
        Thread t4 = new MyThread();
        Thread t5 = new MyThread();
        pool.execute(t1);
        pool.execute(t2);
        pool.execute(t3);
        pool.execute(t4);
        pool.execute(t5);
        pool.shutdown();

    }
}

class MyThread extends Thread {
    @Override
    public void run() {
        // TODO Auto-generated method stub
        super.run();
        System.out.println(Thread.currentThread().getName() + "正在执行。。。");
    }

}

执行结果:
pool-1-thread-1正在执行。。。
pool-1-thread-1正在执行。。。
pool-1-thread-1正在执行。。。
pool-1-thread-1正在执行。。。
pool-1-thread-1正在执行。。。
线程池中只有一个线程在执行,看newSingleThreadExecutor的实现

new ThreadPoolExecutor(1, 1,
                                    0L, TimeUnit.MILLISECONDS,
                                    new LinkedBlockingQueue<Runnable>())

corePoolSize是1,keepAliveTime是0,也就是没有,LinkedBlockingQueue缓冲队列,无界队列,将导致在所有 corePoolSize 线程都忙时新任务在队列中等待。这样,创建的线程就不会超过 corePoolSize,所以同时就只有一个线程在执行。

二 newCachedThreadPool

public class ExecutorTest {
    public static void main(String[] args) {
//      ExecutorService pool = Executors.newSingleThreadExecutor();
        ExecutorService pool = Executors.newCachedThreadPool();
//      ExecutorService executorService3 = Executors.newSingleThreadExecutor();
//      ExecutorService executorService4 = Executors.newScheduledThreadPool(5);
        Thread t1 = new MyThread();
        Thread t2 = new MyThread();
        Thread t3 = new MyThread();
        Thread t4 = new MyThread();
        Thread t5 = new MyThread();
        pool.execute(t1);
        pool.execute(t2);
        pool.execute(t3);
        pool.execute(t4);
        pool.execute(t5);
        pool.shutdown();

    }
}

class MyThread extends Thread {
    @Override
    public void run() {
        // TODO Auto-generated method stub
        super.run();
        System.out.println(Thread.currentThread().getName() + "正在执行。。。");
    }

}

执行结果
pool-1-thread-1正在执行。。。
pool-1-thread-4正在执行。。。
pool-1-thread-3正在执行。。。
pool-1-thread-2正在执行。。。
pool-1-thread-5正在执行。。。
线程中有5个线程在执行,看源码

new ThreadPoolExecutor(0, Integer.MAX_VALUE,
                                      60L, TimeUnit.SECONDS,
                                      new SynchronousQueue<Runnable>())

核心线程数是0,SynchronousQueue是直接提交,Integer.MAX_VALUE相当于最大值,每次添加任务的时候,直接创建一个新的线程执行,如果有空闲线程超过60秒,就移除。

三 newFixedThreadPool

public class ExecutorTest {
    public static void main(String[] args) {
//      ExecutorService pool = Executors.newSingleThreadExecutor();
//      ExecutorService pool = Executors.newCachedThreadPool();
        ExecutorService pool = Executors.newFixedThreadPool(3);
//      ExecutorService executorService4 = Executors.newScheduledThreadPool(5);
        Thread t1 = new MyThread();
        Thread t2 = new MyThread();
        Thread t3 = new MyThread();
        Thread t4 = new MyThread();
        Thread t5 = new MyThread();
        pool.execute(t1);
        pool.execute(t2);
        pool.execute(t3);
        pool.execute(t4);
        pool.execute(t5);
        pool.shutdown();

    }
}

class MyThread extends Thread {
    @Override
    public void run() {
        // TODO Auto-generated method stub
        super.run();
        System.out.println(Thread.currentThread().getName() + "正在执行。。。");
    }

}

执行结果:
pool-1-thread-1正在执行。。。
pool-1-thread-3正在执行。。。
pool-1-thread-2正在执行。。。
pool-1-thread-2正在执行。。。
pool-1-thread-3正在执行。。。
同时有三个线程在执行,看源码:

new ThreadPoolExecutor(nThreads, nThreads,
                                      0L, TimeUnit.MILLISECONDS,
                                      new LinkedBlockingQueue<Runnable>());

核心线程数是传进来的,用户自己定义,我demo中定义3个,LinkedBlockingQueue缓冲队列,无界队列,将导致在所有 corePoolSize 线程都忙时新任务在队列中等待。这样,创建的线程就不会超过 corePoolSize,所以同时就有nThreads个线程在执行。

四 newScheduledThreadPool

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class ExecutorTest {
    public static void main(String[] args) {
//      ExecutorService pool = Executors.newSingleThreadExecutor();
//      ExecutorService pool = Executors.newCachedThreadPool();
//      ExecutorService pool = Executors.newFixedThreadPool(3);
        ScheduledExecutorService  pool = Executors.newScheduledThreadPool(3);
        Thread t1 = new MyThread();
        Thread t2 = new MyThread();
        Thread t3 = new MyThread();
        Thread t4 = new MyThread();
        Thread t5 = new MyThread();
        pool.schedule(t1, 0, TimeUnit.SECONDS);
        pool.schedule(t2, 10, TimeUnit.SECONDS);
        pool.schedule(t3, 15, TimeUnit.SECONDS);
        pool.schedule(t4, 20, TimeUnit.SECONDS);
        pool.schedule(t5, 25, TimeUnit.SECONDS);


    }
}

class MyThread extends Thread {
    @Override
    public void run() {
        // TODO Auto-generated method stub
        super.run();
        System.out.println(Thread.currentThread().getName() + "正在执行。。。");
    }

}

执行结果:
pool-1-thread-1正在执行。。。
pool-1-thread-2正在执行。。。
pool-1-thread-3正在执行。。。
pool-1-thread-1正在执行。。。
pool-1-thread-2正在执行。。。
每隔5,10,15,20,25秒支持一个线程,有点定时器的感觉,看源码:

super(corePoolSize, Integer.MAX_VALUE, 0, NANOSECONDS,
              new DelayedWorkQueue());

核心线程数是用户自己定义传进去的,刚才我传了3个,所以这里有3个线程在同时执行,DelayedWorkQueue这个队列暂时我还没深入研究,这里先不讲,先知道怎么用就行了。

前面一直执行的是实现Runnable的线程,这种没有返回值,如果希望有返回值,那么就要支持实现Callable接口的线程,Callable中的call()方法类似Runnable的run()方法,区别同样是有返回值,后者没有,当将一个Callable的对象传递给ExecutorService的submit方法,则该call方法自动在一个线程上执行,并且会返回执行结果Future对象。同样,将Runnable的对象传递给ExecutorService的submit方法,则该run方法自动在一个线程上执行,并且会返回执行结果Future对象,但是在该Future对象上调用get方法,将返回null。如下:

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class ExecutorTest {
    public static void main(String[] args) {
        ExecutorService pool = Executors.newCachedThreadPool();
        List<Future<String>> list = new ArrayList<Future<String>>();
        for (int i = 0; i < 10; i++) {
            Future<String> future = pool.submit(new ThreadWithResult());
            list.add(future);
        }
        for(Future<String> future:list){
            try{
                while(!future.isDone());
                    System.out.println(future.get());
            }catch(Exception e){
                e.printStackTrace();
            }
        }
        pool.shutdown();
    }

}

class ThreadWithResult implements Callable<String> {

    @Override
    public String call() throws Exception {
        // TODO Auto-generated method stub
        System.out.println("call()  " + Thread.currentThread().getName());
        return Thread.currentThread().getName();
    }

}

执行结果:
call() pool-1-thread-3
call() pool-1-thread-9
call() pool-1-thread-8
call() pool-1-thread-7
call() pool-1-thread-6
call() pool-1-thread-5
call() pool-1-thread-4
call() pool-1-thread-2
call() pool-1-thread-1
pool-1-thread-1
pool-1-thread-2
pool-1-thread-3
pool-1-thread-4
pool-1-thread-5
pool-1-thread-6
pool-1-thread-7
pool-1-thread-8
pool-1-thread-9
call() pool-1-thread-10
pool-1-thread-10
注意:如果Future的返回尚未完成,则get()方法会阻塞等待,直到Future完成返回,可以通过调用isDone()方法判断Future是否完成了返回。
还有一个类需要说明下,CompletionService,把刚才的代码修改下:

import java.util.concurrent.Callable;
import java.util.concurrent.CompletionService;
import java.util.concurrent.ExecutorCompletionService;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class ExecutorTest {
    public static void main(String[] args) {
        ExecutorService pool = Executors.newCachedThreadPool();
        CompletionService<String> comp = new ExecutorCompletionService<>(pool); 
        for (int i = 0; i < 10; i++) {
            comp.submit(new ThreadWithResult());
        }
        for(int i = 0; i < 10; i++){
            try{
                Future<String> future = comp.take();
                System.out.println(future.get());
            }catch(Exception e){
                e.printStackTrace();
            }
        }
        pool.shutdown();
    }

}

class ThreadWithResult implements Callable<String> {

    @Override
    public String call() throws Exception {
        // TODO Auto-generated method stub
        System.out.println("call()  " + Thread.currentThread().getName());
        return Thread.currentThread().getName();
    }

}

跟普通ExecutorService不同的是,CompletionService维护了一个队列,只有当这个Future对象状态是结束的时候,才会加入到这个Queue中,这样我们就不需要自己定义一个List了,并且取出来的时候也不是按之前List排好的顺序,而是谁先返回,谁先得到。

总结:关于Executor,几个比较关键的类,Executor,Executors,ExecutorService,Future,Callable,CompletionService。还要理清线程核心数,最大线程数,队列的三种排队方式,写的比较仓促,有问题,欢迎指正。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值