1. 概述
在本教程中,我们将讨论孵化器特性结构化并发(JEP 428),它为Java 19提供了结构化并发的能力。我们将指导您使用新的API来管理多线程代码。
2. 理念
通过采用减少线程泄漏和取消延迟可能性的并发编程风格,增强多线程代码的可维护性、可靠性和可观察性,这些是与取消和关闭相关的常见风险。为了更好地理解非结构化并发的问题,让我们看一个例子:
Future``<Shelter>`` shelter;
Future`<List```<Dog>````> dogs;
try (ExecutorService executorService = Executors.newFixedThreadPool(3)) {
shelter = executorService.submit(this::getShelter);
dogs = executorService.submit(this::getDogs);
Shelter theShelter = shelter.get(); // 等待shelter
List```<Dog>``` theDogs = dogs.get(); // 等待dogs
Response response = new Response(theShelter, theDogs);
} catch (ExecutionException | InterruptedException e) {
throw new RuntimeException(e);
}
大约 3 分钟