java线程池countlauch_Java-线程池和CountDownLatch结合返回执行结果

CountDownLatch和线程池结合,返回执行结果

优雅关闭线程池,参考https://www.cnblogs.com/goodA…

import java.util.concurrent.ArrayBlockingQueue;

import java.util.concurrent.CountDownLatch;

import java.util.concurrent.ThreadPoolExecutor;

import java.util.concurrent.TimeUnit;

public class TaskWorkerMain {

static ThreadPoolExecutor taskExecutor = new ThreadPoolExecutor(20, 50, 0L, TimeUnit.MILLISECONDS,

new ArrayBlockingQueue(100));

public static void main(String[] args) {

CountDownLatch latch = new CountDownLatch(3);

TaskWorker worker1 = new TaskWorker(latch, "1");

TaskWorker worker2 = new TaskWorker(latch, "2");

TaskWorker worker3 = new TaskWorker(latch, "3");

// 利用线程池执行线程

taskExecutor.execute(worker1);

taskExecutor.execute(worker2);

taskExecutor.execute(worker3);

try {

latch.await(5000, TimeUnit.MILLISECONDS);// 设置超时时间为5秒

} catch (InterruptedException e) {

e.printStackTrace();

} finally {

if (latch.getCount() == 0f) {

System.out.println("worker1:" + worker1.getResultMsg() + "\nworker2:" + worker2.getResultMsg()

+ "\nworker3:" + worker3.getResultMsg());

}

taskExecutor.shutdown(); // Disable new tasks from being submitted

// 设定最大重试次数

try {

// 等待 60 s

if (!taskExecutor.awaitTermination(60, TimeUnit.SECONDS)) {

// 调用 shutdownNow 取消正在执行的任务

taskExecutor.shutdownNow();

// 再次等待 60 s,如果还未结束,可以再次尝试,或则直接放弃

if (!taskExecutor.awaitTermination(60, TimeUnit.SECONDS))

System.err.println("线程池任务未正常执行结束");

}

} catch (InterruptedException ie) {

// 重新调用 shutdownNow

taskExecutor.shutdownNow();

}

}

}

}

class TaskWorker implements Runnable{

private CountDownLatch countDownLatch;

private String requestParam;

private String resultMsg = "";

private String resultErrMsg;

public TaskWorker(CountDownLatch countDownLatch, String requestParam) {

super();

this.countDownLatch = countDownLatch;

this.requestParam = requestParam;

}

@Override

public void run() {

String result = "";

try {

//TODO 逻辑代码

result = doRealLogic(requestParam);

//设置返回值

setResultMsg(result);

} catch (Exception e) {

setResultErrMsg(e.getMessage());

}finally {

countDownLatch.countDown();

}

}

/**

* 真实逻辑代码

* @param requestParam

* @return

*/

private String doRealLogic(String requestParam) {

return requestParam;

}

public String getResultMsg() {

return resultMsg;

}

public void setResultMsg(String resultMsg) {

this.resultMsg = resultMsg;

}

public String getResultErrMsg() {

return resultErrMsg;

}

public void setResultErrMsg(String resultErrMsg) {

this.resultErrMsg = resultErrMsg;

}

}

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、付费专栏及课程。

余额充值