跳转到内容
View in the app

A better way to browse. Learn more.

彼岸论坛

A full-screen app on your home screen with push notifications, badges and more.

To install this app on iOS and iPadOS
  1. Tap the Share icon in Safari
  2. Scroll the menu and tap Add to Home Screen.
  3. Tap Add in the top-right corner.
To install this app on Android
  1. Tap the 3-dot menu (⋮) in the top-right corner of the browser.
  2. Tap Add to Home screen or Install app.
  3. Confirm by tapping Install.
欢迎抵达彼岸 彼岸花开 此处谁在 -彼岸论坛

[Java] 求助: Java 多线程如何终止其它线程

发表于

主线程去调用 10 个子线程查询任务(返回 true/false), 在回调中统计结果,
我想在得到两个 true 时主线程立即返回 true, 不管其他的子线程时已提交到线程池还是未提交到线程池, 都不需要了

我尝试了CompletableFuture#cancel, 和Executor#shutDownNow方法, 都没达到效果

ThreadPoolExecutor executor = newFixedThreadFool(10);
List<CompletableFuture<Boolean> list = ... //10 个任务, 都提交到 executor
AtomicInteger i = 0;
list.forEach(cf-
	cf.thenAccept(b->
		if(b && i.incrementAndGet >= 2 ){
			//让主线程停止阻塞立即返回, 尝试下面两个方案都不行
			executor.shutDownNow();
			list.forEach(f->f.cancel(true));
		} 
))
// 希望通过某种方式让此处停止阻塞
CompletableFuture.allOf(list.toArray).join()

return i.get()>=2;

目前的方案是把后续流程放在了子线程回调中, 加锁处理, 主线程不要返回值了, 应该是可行的,
但是还是想请问大家, 原来的"主线程提前返回"的想法能否实现?

Featured Replies

No posts to show

创建帐户或登录来提出意见

Configure browser push notifications

Chrome (Android)
  1. Tap the lock icon next to the address bar.
  2. Tap Permissions → Notifications.
  3. Adjust your preference.
Chrome (Desktop)
  1. Click the padlock icon in the address bar.
  2. Select Site settings.
  3. Find Notifications and adjust your preference.