关于 Executor 和 ExecutorService

一、Executor:

  • 是一个接口

  • 用于执行提交的任务

  • 解耦任务提交和执行(线程的创建及调度)

Executor的实现可以根据实际需求延展不同的逻辑:

1、对于提交的任务同步或者异步执行,如下同步执行:

class ThreadPerTaskExecutor implements Executor {
   public void execute(Runnable r) {
     new Thread(r).start();
}

2、另起线程执行任务,如下:

 class ThreadPerTaskExecutor implements Executor {
     public void execute(Runnable r) {
     new Thread(r).start();
 }

3、对于执行的任务添加限制:

class SerialExecutor implements Executor {
   final Queue<Runnable> tasks = new ArrayDeque<Runnable>();
   final Executor executor;
   Runnable active;

   SerialExecutor(Executor executor) {
     this.executor = executor;
   }

   public synchronized void execute(final Runnable r) {
     tasks.offer(new Runnable() {
       public void run() {
         try {
           r.run();
         } finally {
           scheduleNext();
         }
       }
     });
     if (active == null) {
       scheduleNext();
     }
   }

   protected synchronized void scheduleNext() {
     if ((active = tasks.poll()) != null) {
       executor.execute(active);
     }
   }
 }}

二、ExecutorService:

  • 任务执行器

  • 提供任务终止方法

  • 返回Future用以跟踪任务执行结果

1、可以被关闭,也就意味着执行器不再接受新任务

shutdown:等待已提交的任务执行完毕后关闭

shutdownNow:阻止等待的任务开始并停止当前运行的任务

对于不再使用的 ExecutorService 需要及时关闭以释放资源

2、submit:创建并返回 Future 对象,用以取消任务或者等待任务执行完成

3、invokeAny、invokeAll:批处理任务,invokeAny 等待任务中任一任务执行完成即返回,invokeAll 等待所有任务执行完成即返回

4、Executors:ExecutorService 工厂类

三、附加订阅

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

windwant

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值