该并行程序需要有返回结果到主线程
时间: 2024-04-15 17:28:24 浏览: 21
如果需要将并行任务的结果返回给主线程,可以使用 Callable 和 Future 来实现。下面是一个示例:
```java
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;
public class CountDownLatchExample {
public static void main(String[] args) throws InterruptedException, ExecutionException {
int taskCount = 3;
CountDownLatch latch = new CountDownLatch(taskCount);
ExecutorService executor = Executors.newFixedThreadPool(taskCount);
List<Future<String>> futures = new ArrayList<>();
for (int i = 0; i < taskCount; i++) {
Future<String> future = executor.submit(new Task(latch));
futures.add(future);
}
latch.await();
System.out.println("All tasks have finished, now executing main task.");
for (Future<String> future : futures) {
String result = future.get();
System.out.println("Task result: " + result);
}
executor.shutdown();
}
static class Task implements Callable<String> {
private CountDownLatch latch;
public Task(CountDownLatch latch) {
this.latch = latch;
}
@Override
public String call() throws Exception {
try {
System.out.println("Task started: " + Thread.currentThread().getName());
Thread.sleep(1000);
System.out.println("Task finished: " + Thread.currentThread().getName());
return "Task result from " + Thread.currentThread().getName();
} finally {
latch.countDown();
}
}
}
}
```
在上面的代码中,我们使用 Callable 接口来定义任务,并将任务提交给线程池。每个任务执行完毕后会返回一个 Future 对象,我们将这些 Future 对象存储在列表中。主线程在等待所有任务完成后,通过遍历 Future 对象列表来获取每个任务的结果。这样我们就可以将并行任务的结果返回给主线程进行处理。
相关推荐
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)