首页 > 解决方案 > 我们什么时候应该在java中使用执行器框架?

问题描述

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

标签: javamultithreadingexecutorserviceexecutor

解决方案


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

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

Web 电子商务应用程序以及其他类型的应用程序中使用的 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();
}
}
}

输出: 起始 A:0 A:1 A:2 A:3 A:4 C:0 C:1 C:2 C:3 C:4 D:0 D:1 D:2 D:3 D:4 B: 0 B:1 B:2 B:3 B:4 完成

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


推荐阅读