带有示例的Java.util.concurrent.ExecutorService 接口
ExecutorService接口通过添加有助于管理和控制线程执行的方法来扩展 Executor。它在Java.util.concurrent 包中定义。它定义了执行返回结果的线程、一组线程并确定关闭状态的方法。
ExecutorService 接口在一个名为Executors的实用程序类中实现。它定义了提供 ExecutorService 接口和许多其他接口的实现的方法,并带有一些默认设置。
类层次结构:
java.util.concurrent
↳ Interface ExecutorService
实现子接口:
ScheduledExecutorService
实现类:
AbstractExecutorService
ForkJoinPool
ScheduledThreadPoolExecutor
ThreadPoolExecutor
Executor 接口中的方法:
1. shutdown() – 调用该函数时,会导致所有当前正在执行的任务在完成后按照启动顺序终止,并拒绝任何新的传入任务。
句法:
void shutdown()
2. shutdownNow() – 在调用时,该函数强制终止所有任务,而不管它们的当前状态,即运行、等待或就绪。返回的处于就绪状态的任务列表。
句法:
List
3. isShutdown() - 该函数告诉调用执行器是否关闭。如果关机返回真,否则返回假。
句法:
boolean isShutdown()
4. isTerminated() - 该函数检查所有任务是否在关机后完成。如果完成返回真,否则返回假。
句法:
boolean isTerminated()
5. awaitTermination() - 该函数在找到关闭请求后等待所有任务完成执行。它等待 timelimit 参数指定的时间。
句法:
boolean awaitTermination(long timelimit, TimeUnit unit) throws InterruptedException
6. submit() - 该函数将返回结果的任务添加到正在执行的任务列表中以供执行。它返回一个 Future 对象,该对象在完成后返回任务的结果。
句法:
1.
2.
3. Future submit?(Runnable task)
7. invokeAll() - 该函数执行集合中包含的所有任务。返回的 Future 对象列表包含各种任务的状态和返回值。
句法:
1.
2.
8. invokeAny() - 该函数执行集合中包含的所有任务。在完成任何单个任务时,它会返回其结果,并且所有其他任务都被取消。
句法:
1.
2.
演示 Executors 的示例
Java
// Java program to demonstrate ExecutorService interface
import java.util.concurrent.*;
public class SimpleExecutor {
public static void main(String[] args)
{
CountDownLatch cd1 = new CountDownLatch(5);
CountDownLatch cd2 = new CountDownLatch(5);
CountDownLatch cd3 = new CountDownLatch(5);
CountDownLatch cd4 = new CountDownLatch(5);
ExecutorService es = Executors.newFixedThreadPool(2);
System.out.println("Starting");
es.execute(new MyThread(cd1, "A"));
es.execute(new MyThread(cd2, "B"));
es.execute(new MyThread(cd3, "C"));
es.execute(new MyThread(cd4, "D"));
try {
cd1.await();
cd2.await();
cd3.await();
cd4.await();
}
catch (InterruptedException e) {
System.out.println(e);
}
es.shutdown();
System.out.println("Done");
}
}
class MyThread implements Runnable {
String name;
CountDownLatch latch;
MyThread(CountDownLatch latch, String name)
{
this.name = name;
this.latch = latch;
new Thread(this);
}
public void run()
{
for (int i = 0; i < 5; i++) {
System.out.println(name + ": " + i);
latch.countDown();
}
}
}
Starting
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
Done
参考: https://docs.oracle.com/javase/9/docs/api/ Java/util/concurrent/ExecutorService.html