lolico 最近的时间轴更新
lolico

lolico

V2EX 第 483150 号会员,加入于 2020-04-12 13:36:57 +08:00
今日活跃度排名 16083
lolico 最近回复了
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
关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   实用小工具   ·   4876 人在线   最高记录 6679   ·     Select Language
创意工作者们的社区
World is powered by solitude
VERSION: 3.9.8.5 · 18ms · UTC 08:00 · PVG 16:00 · LAX 01:00 · JFK 04:00
Developed with CodeLauncher
♥ Do have faith in what you're doing.