
ExecutorService是Java并发编程中管理线程池的核心接口,允许我们提交任务(Callable或Runnable)并异步执行。Future接口代表异步计算结果,提供检查计算是否完成、等待计算完成、获取计算结果的方法。
当向executorservice提交callable任务时,您将返回future对象。通过这个future对象,我们可以使用get()方法来获得任务的执行结果。get()方法包括带有超时参数的阻塞版本和版本。带有超时参数的get(long timeout, TimeUnit unit)该方法将在规定的时间内等待任务完成并返回结果。如果超时尚未完成,则抛出timeoutexception。
Shutdown()和awaitTermination()方法通常涉及ExecutorService的生命周期管理。shutdown()该方法用于启动线程池的优雅关闭过程,拒绝新任务,但允许已提交的任务继续执行。awaitTermination(long timeout, TimeUnit unit)在所有任务完成、超时到达或当前线程中断之前,方法将阻塞当前线程。
2. Future.get()ExecutorService.awaitTermination()交互分析考虑到以下代码片段,它显示了Future.get()ExecutorService.awaitTermination()组合使用:
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;
public class ExecutorServiceTimeoutDemo {
// 假设这是一个长期模拟Callable任务
static class MyCallable implements Callable<String> {
private final String name;
private final long sleepMillis;
public MyCallable(String name, long sleepMillis) {
this.name = name;
this.sleepMillis = sleepMillis;
}
@Override
public String call() throws Exception {
System.out.println(name + " started.");
Thread.sleep(sleepMillis); // 执行模拟任务的时间
System.out.println(name + " finished.");
return "Result of " + name;
}
}
public static void main(String[] args) {
// 创建一个固定大小为2的线程池
ExecutorService executorService = Executors.newFixedThreadPool(2);
List<Callable<String>> callables = new ArrayList<>();
// 假设 task1 耗时 4 分钟
callables.add(new MyCallable("Task1", 4 * 60 * 1000));
// 假设 task2 耗时 6 分钟
callables.add(new MyCallable("Task2", 6 * 60 * 1000));
List<Future<String>> futures = null;
try {
// 提交所有任务,invokeall将返回Future列表
futures = executorService.invokeAll(callables);
System.out.println("Attempting to get results with 5-minute timeout for each task...");
// 获得第一个任务的结果,设置5分钟超时
// 假设Task1实际上需要4分钟,这里将等待4分钟
String result1 = futures.get(0).get(5, TimeUnit.MINUTES);
System.out.println("Got " + result1);
// 获得第二个任务的结果,设置5分钟超时
// 假设Task2实际上需要6分钟,Timeoutexception将在这里等待5分钟
String result2 = futures.get(1).get(5, TimeUnit.MINUTES);
System.out.println("Got " + result2);
} catch (InterruptedException e) {
System.err.println("Execution interrupted: " + e.getMessage());
Thread.currentThread().interrupt(); // Restore interrupt status
} catch (ExecutionException e) {
System.err.println("Task execution failed: " + e.getCause().getMessage());
} catch (TimeoutException e) {
System.err.println("Task timed out: " + e.getMessage());
// 超时后,任务可能仍在运行
} finally {
// Executorservice关闭
executorService.shutdown();
System.out.println("ExecutorService shutdown initiated.");
// 等待ExecutorService终止,设置30秒超时
try {
if (!executorService.awaitTermination(30, TimeUnit.SECONDS)) {
System.err.println("ExecutorService did not terminate gracefully within 30 seconds. Forcing shutdown...");
executorService.shutdownNow(); // 强制关闭
} else {
System.out.println("ExecutorService terminated gracefully.");
}
} catch (InterruptedException e) {
System.err.println("Await termination interrupted: " + e.getMessage());
Thread.currentThread().interrupt();
executorService.shutdownNow();
}
}
}
}
代码执行流程及加时计算:
-
executorService.invokeAll(callables);: 这一步将两个callable任务提交到线程池。invokeall方法将被阻塞,直到所有任务完成,或中断,或任务抛出异常。它返回到一个list
>,每个Future对应一个提交的任务。 - 注意: 在taskslist(包括calable对象)上直接调用原始问题中的代码是错误的。get()方法应在invokeAll返回的Future对象上调用。上述示例已修改此逻辑。
-
futures.get(0).get(5, TimeUnit.MINUTES);:
- 代码将阻塞当前线程,等待第一个任务(Task1)完成,最长等待5分钟。
- 如果Task1实际上在4分钟内完成,当前线程将等待4分钟。
- 如果Task1实际上超过5分钟还没有完成,get()方法将抛出Timeoutexception,但Task1本身可能仍在后面继续在台线程中运行。
- 最大等待时间:5分钟。
-
futures.get(1).get(5, TimeUnit.MINUTES);:
- 该行代码只能在第一个get()调用完成后执行(无论是正常完成还是超时抛出异常)。它会阻塞当前线程,等待第二个任务(Task2)完成,最长等待5分钟。
- 假如Task2实际上是在6分钟内完成的,因为这里设置了5分钟的超时,get()方法将在5分钟后抛出Timeoutexception。
- 最大等待时间:5分钟。
-
executorService.shutdown();:
- 两个Future.get()调用完成后(或加时),即可调用此方法。它将启动优雅的线程池关闭。此时,Task1和Task2应该已经完成(或至少Future.get()已处理其结果/超时)。如果任务因get()超时而仍在运行,shutdown()允许它们继续完成。
-
executorService.awaitTermination(30, TimeUnit.SECONDS);:
- 这种方法在shutdown()之后调用,会堵塞当前线程,最长等待30秒,以确保所有提交的任务(包括可能因get()加班但仍在后台运行的任务)都已完成,线程池中的线程已终止。
- 假如此时线程池中没有活动任务,或者所有任务都在很短的时间内完成,这种方法将很快返回true。
- 最大等待时间:30秒。
总等待时间计算:
因为Future.get()调用是按顺序执行的,而awaittermination()是在所有get()调用后才开始等待的,所以它们的超时时间是累积的。
- 第一个get()最大等待:5分钟
- 第二个get()最大等待:5分钟
- awaitTermination()最大等待:30秒
因此,在最坏的情况下(即每个get()达到最大超时,awaittermination也需要等待最大时间),总等待时间为:5分钟 + 5分钟 + 30秒 = 10分钟30秒。
问题的关键在于,Future.get()加班是为了完成单个任务,顺序被堵塞。awaittermination()的加班是为了终止整个线程池中所有未完成的任务,发生在get()调用后。短短30秒的awaittermination加班不会“覆盖”Future.get()5分钟加时,因为它们作用于不同的阶段和对象。
3. 注意事项和最佳实践- 理解阻塞点: 一定要清楚Futureee.get()是一个堵塞操作。如果在循环中将get()调用到多个future对象,那么这些get()操作将被顺序堵塞,而不是并行堵塞。这意味着下一个get()将在前一个get()完成(或加班)后开始。
- 错误处理: Future.get()方法将抛出InterruptedException、ExecutionExceptionTimeoutException。在实际应用中,必须捕获并妥善处理这些异常。Timeoutexception尤为重要,这意味着任务未能在指定时间内完成,任务可能仍在后台运行。
- 优雅关闭: executorService总是先调用executor.shutdown()然后调用executorservice.awaitTermination()。shutdown()是启动关闭过程的信号,而awaittermination()等待过程完成。
- 强制关闭: 如果awaittermination()返回false(表示未能在指定时间内终止),通常应考虑调用executerservice.shutdownNow()强制关闭线程池。shutdownNow()试图中断所有正在执行的任务,并停止所有等待的任务。
-
并行等待多个任务: 如果需要平行等待多个任务的结果,并且希望所有任务的等待时间都有一个共同的上限,则不应简单地调用多个future.get()。可考虑以下策略:
- 使用Completablefure.allOf(): 若使用Java 8及更高版本,CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])可用于等待所有Completablefuture完成,然后进行超时控制。
- 管理Future列表: 所有Future都可以放入列表中,然后通过循环遍历列表,为每个Future设置加时,但要知道这仍然是顺序堵塞。
- 更复杂的协调: 自定义线程池或使用更先进的并发工具可能需要更复杂的加班需求。
Future.get()ExecutorService.awaitTermination()是Java并发编程中管理任务结果和线程池生命周期的重要工具。了解其各自的功能范围、执行顺序和加班机制是避免长期事故堵塞的关键。当它们按顺序使用时,它们的加班时间是累积的,而不是简单地取最短值。正确处理这些加班和异常,合理设计线程池的关闭逻辑,可以保证并发程序的强度和可控性。
以上是对Futureee的理解.get()ExecutorService.awaitTermination()关于超时机制的详细信息,请关注图灵教育的其他相关文章!