V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
V2EX  ›  lolico  ›  全部回复第 1 页 / 共 1 页
回复总数  11
4 天前
回复了 Alextrasza 创建的主题 Java 求助: Java 多线程如何终止其它线程
@lolico 这里用线程池也是可以的,主线程 latch.await()后调线程池 shutdownNow 也可以中断线程池内所有线程
4 天前
回复了 Alextrasza 创建的主题 Java 求助: Java 多线程如何终止其它线程
public static void main(String[] args) throws InterruptedException {
List<Thread> threads = new ArrayList<>();
final int untilSuccessCount = 2;
final int threadCount = 10;
AtomicInteger counter = new AtomicInteger(0);
CountDownLatch latch = new CountDownLatch(1);
for (int i = 0; i < threadCount; i++) {
int finalI = i;
Thread thread = new Thread(() -> {
// 模拟耗时任务
Random random = new Random();
// 直接使用线程的 interrupt 中断标记
while (!Thread.interrupted()) {
try {
Thread.sleep((long) finalI * 1000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
return;
}
if (random.nextBoolean()) {
if (counter.incrementAndGet() == untilSuccessCount) {
latch.countDown();
}
return;
}
}
});
thread.start();
threads.add(thread);
}
// 可以启动一个线程,等待所有 thread 完成后 latch.countDown ,防止一直等待。
// 或者加一个 allDoneLatch 也可以实现
latch.await();
threads.forEach(Thread::interrupt); // 中断其他线程
System.out.println(counter.get());
}
支持一下
祝老板大卖!
支持一下
2023-09-05 13:08:45 +08:00
回复了 StoneHuLu 创建的主题 问与答 ubuntu 服务器上如何搭建 httpproxy?
2023-08-24 11:58:45 +08:00
回复了 zzxin 创建的主题 推广 [抽奖+优惠]女朋友做了一款超好用的固体洗发水。
分母+1
2022-03-11 13:35:59 +08:00
回复了 luvroot 创建的主题 互联网 yuque vip 活动可以领到 1 年的
接力邀请码:RQF7SW
关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   实用小工具   ·   2578 人在线   最高记录 6679   ·     Select Language
创意工作者们的社区
World is powered by solitude
VERSION: 3.9.8.5 · 24ms · UTC 10:32 · PVG 18:32 · LAX 03:32 · JFK 06:32
Developed with CodeLauncher
♥ Do have faith in what you're doing.