java线程池中何使用CountDownLatch和Future来实现等待所有线程执行完毕并获取返回值的

如果你需要使用Callable接口来替代Runnable接口来执行任务,可以使用ExecutorService.submit(Callable)方法来提交任务,该方法会返回一个Future对象,该对象可以用来获取任务的返回值。

以下是一个示例代码,展示了如何使用CountDownLatch和Future来实现等待所有线程执行完毕并获取返回值的功能:

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;

public class WaitThreadExample {
    public static void main(String[] args) {
        int nThreads = 5;
        CountDownLatch latch = new CountDownLatch(nThreads);
        ExecutorService executor = Executors.newFixedThreadPool(nThreads);
        List<Future<Integer>> futures = new ArrayList<>();

        for (int i = 0; i < nThreads; i++) {
            futures.add(executor.submit(new Callable<Integer>() {
                public Integer call() throws Exception {
                    // 线程执行任务
                    System.out.println("Thread " + Thread.currentThread().getName() + " is running");
                    // 计数器减1
                    latch.countDown();
                    return 1; // 返回值
                }
            }));
        }

        // 等待所有线程执行完毕
        try {
            latch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        // 输出结果
        int sum = 0;
        for (Future<Integer> future : futures) {
            try {
                sum += future.get(); // 获取返回值并累加
            } catch (InterruptedException | ExecutionException e) {
                e.printStackTrace();
            }
        }
        System.out.println("All threads have finished executing");
        System.out.println("Sum of return values: " + sum);

        // 关闭线程池
        executor.shutdown();
    }
}

上述代码与之前的示例代码类似,但是使用了Callable接口来执行任务,提交任务的方法也由executor.submit(Runnable)变为了executor.submit(Callable),同时List<Future> futures用来存储每个任务的Future对象,以便在所有任务执行完毕后获取它们的返回值。在每个Callable任务的call()方法中,除了执行任务之外,还使用latch.countDown()方法将计数器的值减1,并返回一个整数值1作为该任务的返回值。

在等待所有线程执行完毕之后,可以使用Future.get()方法获取每个任务的返回值,并将它们累加到sum变量中。最后输出计数器的值以及所有任务的返回值之和,并关闭线程池。

执行上述代码的结果应该是类似于以下的输出:

Thread pool-1-thread-2 is running
Thread pool-1-thread-1 is running
Thread pool-1-thread-3 is running
Thread pool-1-thread-4 is running
Thread pool-1-thread-5 is running
All threads have finished executing
Sum of return values: 5
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java,可以使用线程池CountDownLatch实现分批删除操作。首先,我们可以定义一个线程池来处理任务。线程池可以提高终端响应速度,同时可以控制并发线程的数量。然后,我们可以使用CountDownLatch实现线等待子任务线执行完毕的功能,以便在所有任务执行完毕后进行结果的汇总和后续操作。 具体实现的代码如下所示: ```java import java.util.List; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class BatchDeleteExample { public void batchDelete(List<String> paramList) { // 创建线程池 ExecutorService executorService = Executors.newFixedThreadPool(paramList.size()); // 创建CountDownLatch,用于等待子任务线执行完毕 CountDownLatch latch = new CountDownLatch(paramList.size()); for (String param : paramList) { executorService.execute(() -> { try { // 执行删除操作 delete(param); } finally { // 子任务线执行完毕,计数器减一 latch.countDown(); } }); } try { // 主线等待子任务线执行完毕 latch.await(); } catch (InterruptedException e) { e.printStackTrace(); } // 所有任务执行完毕,进行结果汇总和后续操作 // ... // 关闭线程池 executorService.shutdown(); } private void delete(String param) { // 执行删除操作 System.out.println("删除:" + param); } } ``` 在上述代码,我们首先创建了一个线程池线程池的大小与任务数量相同,以便每个任务都能被一个线程处理。然后,我们创建了一个CountDownLatch,其初始计数器的为任务数量。在每个子任务线,我们执行了删除操作,并在finally块将计数器减一。主线程调用latch.await()方法等待所有子任务线执行完毕。最后,我们可以在所有任务执行完毕后进行结果的汇总和后续操作。 这样,通过线程池CountDownLatch的结合使用,我们可以实现分批删除操作,并且保证主线程在所有子任务线执行完毕后继续往下执行。 #### 引用[.reference_title] - *1* *2* *3* [线程池CountDownLatch结合使用详解](https://blog.csdn.net/qldd/article/details/126631846)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值