我试图在我的程序中引入并发性。程序的结构是这样的:
ThreadPoolExecutor executor = (ThreadPoolExecutor) Executors.newFixedThreadPool(5);
List<String> initialData = dao.fetchFromDB("input");
Queue queue = new MyQueue();
queue.add(initialData);
while(queue.length() > 0) {
int startingLength = queue.length();
for (int i = 0; i < startingLength; i++) {
String input = queue.remove();
if(input.equals("some value")) {
missionAccomplished = true;
break;
} else {
MyRunnable task = new MyRunnable(input, queue, dao);
executor.execute(task);
}
}
if(missionAccomplished) {
break;
}
executor.shutdown();
}
所以队列中包含了需要逐一处理的数据。在while循环中,我运行一个for循环,它依次从队列中挑选数据,并对其执行一些检查,如果检查失败,我用该数据创建一个可运行的任务,并将其交给执行器(由于DB操作耗时,我想使用并行性)。For循环在给定的while迭代中只选取一定长度以内的数据。我想要实现的是,只有当当前迭代中提交给executor的所有任务完成时,'while'循环才会进入下一个迭代。
如何做到这一点?
try-with-resources inProject Loom
你问:
我想要实现的是'while'循环只在当前迭代中提交给executor的所有任务完成时才进入下一个迭代。
Project Loom承诺使这更简单。
Project Loom带来的变化之一是ExecutorService
接口是AutoCloseable
的子接口。这意味着我们可以使用try-with-resources语法。try-with-resources自动阻塞,直到所有提交的任务完成/失败/取消-正是你所要求的。
同时,退出try
时,会自动关闭executor服务。这些变化意味着你的代码变得更简单、更清晰。
Executors.newVirtualThreadExecutor
。
Project Loom的实验版本现在可用,基于早期访问的Java 17。织机团队正在征求反馈。欲了解更多信息,请参阅Oracle的Ron Pressler最近的演讲和采访。
System.out.println( "INFO - executor service about to start. " + Instant.now() );
try (
ExecutorService executorService = Executors.newVirtualThreadExecutor() ;
)
{
for ( int i = 0 ; i < 7 ; i++ )
{
executorService.submit( ( ) -> System.out.println( Instant.now() ) );
}
}
// Notice that when reaching this point we block until all submitted tasks still running are fin
// because that is the new behavior of `ExecutorService` being `AutoCloseable`.
System.out.println( "INFO - executor service shut down at this point. " + Instant.now() );
运行时。
INFO - executor service about to start. 2021-02-08T06:27:03.500093Z
2021-02-08T06:27:03.554440Z
2021-02-08T06:27:03.554517Z
2021-02-08T06:27:03.554682Z
2021-02-08T06:27:03.554837Z
2021-02-08T06:27:03.555015Z
2021-02-08T06:27:03.555073Z
2021-02-08T06:27:03.556675Z
INFO - executor service shut down at this point. 2021-02-08T06:27:03.560723Z