我们什么时候应该在java中使用执行器框架?



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

并发API提供了一个名为执行器的特性,此外,并发API定义了三个预定义的执行器类: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();
}
}
}

输出:开始答:0答:1答:2答:3答:4C: 0C: 1C: 2C: 3C: 4D: 0D: 1D: 2D: 3D: 4B: 0B: 1B: 2B: 3B: 4做

进一步阅读,我建议阅读Brian Goetz的《Concurrency in Practice》

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

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

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

最新更新