【问题标题】:when should we use executor framework in java?我们什么时候应该在java中使用执行器框架?
【发布时间】:2021-08-09 12:16:19
【问题描述】:

根据多线程,如果我们想在更短的时间内同时执行多个任务,我们会使用它。 但从未真正得到实时项目的使用? 我的意思是,我们究竟可以在哪里使用这个执行器框架,我们在其中创建一个线程池,它们将执行特定的任务。 这可以是什么应用程序,为什么更喜欢它而不是使用 runnable 的普通线程实现?

【问题讨论】:

  • 我使用的是 Java EE 服务器,必须使用注入的 ManagedExecutorService 来启动任务

标签: java multithreading executorservice executor


【解决方案1】:

并发 API 提供了一个名为 executor 的特性,此外,并发 API 定义了三个预定义的 executor 类:ThreadPoolExecutor, ScheduledThreadPoolExecutor 和 ForkJoinPool

池线程提供一组线程,用于执行各种任务,而不是每个任务使用自己的线程,

在网络电子商务应用程序以及其他类型的应用程序中使用的 Executor 框架,

以下程序说明了 Executor 框架的使用:

import java.util.concurrent.*;
class SimpExec {
  public static void main(String args[]) {
  CountDownLatch cdl = new CountDownLatch(5);
  CountDownLatch cdl2 = new CountDownLatch(5);
  CountDownLatch cdl3 = new CountDownLatch(5);
  CountDownLatch cdl4 = new CountDownLatch(5);
  ExecutorService es = Executors.newFixedThreadPool(2);
  System.out.println("Starting");
  // Start the threads.
  es.execute(new MyThread(cdl, "A"));
  es.execute(new MyThread(cdl2, "B"));
  es.execute(new MyThread(cdl3, "C"));
  es.execute(new MyThread(cdl4, "D"));
  try {
  cdl.await();
  cdl2.await();
  cdl3.await();
  cdl4.await();
  } catch (InterruptedException exc) {
    System.out.println(exc);
  }
   es.shutdown();
  System.out.println("Done");
  }
  }


 class MyThread implements Runnable {
 String name;
 CountDownLatch latch;
 MyThread(CountDownLatch c, String n) {
 latch = c;
 name = n;
 new Thread(this);
 }
 public void run() {
for(int i = 0; i < 5; i++) {
 System.out.println(name + ": " + i);
latch.countDown();
}
}
}

输出: 开始 答:0 答:1 A2 答:3 答:4 C: 0 C: 1 C: 2 C: 3 C: 4 D: 0 D: 1 D: 2 D: 3 D: 4 乙:0 乙:1 乙:2 乙:3 乙:4 完成

为了进一步阅读,我建议阅读 Brian Goetz 的 Concurrency in Practice

【讨论】:

    【解决方案2】:

    在许多情况下,您可以利用executor framework,例如异步发送邮件或传输文件等。

    为什么比使用 runnable 的普通线程实现更喜欢它?

    首先,使用线程池的主要好处是它通过避免在请求或任务处理期间创建线程来减少响应时间。其次,executor框架处理线程管理,所以你不需要管它。

    【讨论】:

      猜你喜欢
      • 2010-10-26
      • 2021-09-07
      • 2011-04-12
      • 2017-03-07
      • 1970-01-01
      • 2023-03-15
      • 2011-08-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多