美文网首页
05-28 Executor 执行器

05-28 Executor 执行器

作者: 小明的爷爷的爸爸 | 来源:发表于2020-05-28 11:32 被阅读0次

    简介:Executor 执行器,通常用在线程池中

    一、Executor 执行器

    具体实现如下:

    /* @since 1.5
     * @author Doug Lea
     */
    public interface Executor {
    
        /**
         * Executes the given command at some time in the future.  The command
         * may execute in a new thread, in a pooled thread, or in the calling
         * thread, at the discretion of the {@code Executor} implementation.
         *
         * @param command the runnable task
         * @throws RejectedExecutionException if this task cannot be
         * accepted for execution
         * @throws NullPointerException if command is null
         */
        void execute(Runnable command);
    }
    

    1.5时,Doug Lea 添加

    二、Executor 同步执行

    可能由于多用线程池,误以为是异步,但是实际上Executor执行器由于包含的是单一的方法,于是具体如何执行可以自己控制。

       Executor executor = (Runnable command) ->command.run();//同步的,指定调用runnable 的 run方法
    
            executor.execute(()->{
    
                System.out.println("thread:"+Thread.currentThread().getName()+" run...");
            });
    

    三、Executor 异步执行

      Executor async = (Runnable command) -> new Thread(command).start();//直接线程来执行任务
            async.execute(()->{
    
                System.out.println("thread:"+Thread.currentThread().getName()+" run...");});
    

    四、Executor的实现 ThreadPoolExecutor 带有线程池的执行器

    public class ThreadPoolExecutor extends AbstractExecutorService {
        
        // 核心线程数
        private volatile int corePoolSize;
        // 最大线程数
        private volatile int maximumPoolSize;
        // 任务队列(当任务太多了,就放在这里排队)
        private final BlockingQueue<Runnable> workQueue;
        // 空闲线程的超时时间,超时就回收它(非core线程)
        private volatile long keepAliveTime;
        // 不解释
        private volatile ThreadFactory threadFactory;
        // 线程池拒绝处理函数(如任务太多了,如何拒绝)
        // 默认策略是:AbortPolicy。要决绝是抛出异常:RejectedExecutionException
        private volatile RejectedExecutionHandler handler;
        
    }
    

    相关文章

      网友评论

          本文标题:05-28 Executor 执行器

          本文链接:https://www.haomeiwen.com/subject/jcpoahtx.html