JAVA中只要有一个线程执行成功,就算执行成功 如何写代码 java 类似于前端JavaScript中的Promise.race([p1,p2,p3...])

该博客介绍了如何在Java中使用CountDownLatch来实现当任意一个线程执行成功后,程序即认为整体执行成功。示例代码创建了10个线程,每个线程随机等待一段时间后完成任务并减少计数器,一旦计数器归零,主线程接收到信号并结束。这类似于前端的Promise.race()函数。
摘要由CSDN通过智能技术生成

问题来自

https://ask.csdn.net/questions/7413376?spm=1005.2025.3001.5141

JAVA中只要有一个线程执行成功,就算执行成功 如何写代码

  • java

类似于前端中的Promise.race([p1,p2,p3...])

使用CountDownLatch

package CountDownLatch;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class CountDownLatchTest {
	public static void main(String[] args) {

		ExecutorService es = Executors.newFixedThreadPool(10);
		CountDownLatch latch = new CountDownLatch(1);
		for (int i = 0; i < 10; i++) {
			es.submit(() -> {
				try {
					long wait = (long) (Math.random() * 1000);
					Thread.sleep(wait);
					System.out.println(wait);
					latch.countDown();
				} catch (InterruptedException e) {
					Thread.currentThread().interrupt();
				}
			});
		}

		// wait for the latch to be decremented by the fast threads
		try {
			latch.await();
			System.out.println("Fast Thead End");
			es.shutdownNow();

		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}

 

119
Fast Thead End
 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值