gpt4 book ai didi

java - 如何在java中找到成功完成的第一个线程的结果?

转载 作者:行者123 更新时间:2023-12-05 04:41:06 24 4
gpt4 key购买 nike

假设有多个线程试图找到一个值,首先找到它的线程应该将输出发送到主线程,所有其他线程都应该终止。示例 -

public class WorkerThread implements Runnable {
@Override
public void run() {
// some long task here, returns int value
}
}

public class Main {
public static void main(String[] args){
// initialize multiple worker threads here
// then get result from the thread that completes first
}
}

我查看了文档并找到了 invokeAny ExecutorService但这将返回任何已成功完成的线程的结果,不一定是第一个。

最佳答案

正如@Andy Turner 所说,使用CompletionService:

    public static class WorkerThread implements Callable<Integer> {
@Override
public Integer call() throws Exception {
int nextInt = new Random().nextInt(10000);
try {
System.out.println("I will cost " + nextInt + " ms to finish job.--" + Thread.currentThread().getName());
Thread.sleep(nextInt);
} catch (InterruptedException ite) {
System.out.println("I am interrupted.--" + Thread.currentThread().getName());
return -1;
}
System.out.println("I am finish.--" + Thread.currentThread().getName());
return nextInt;
}
}

public static void main(String[] args) throws InterruptedException, ExecutionException {
int nums = 3;
ExecutorService executorService = Executors.newFixedThreadPool(nums);
CompletionService<Integer> completionService = new ExecutorCompletionService<>(executorService);
while (nums-- > 0) {
completionService.submit(new WorkerThread());
}
Integer firstValue = completionService.take().get();
System.out.println("FirstValue is " + firstValue);
executorService.shutdownNow();
}

你可以在输出中看到,只有一个线程会完成工作(因为只调用一次completionService#take), 其他线程会被中断退出:

I will cost 8943 ms to finish job.--pool-1-thread-1
I will cost 9020 ms to finish job.--pool-1-thread-2
I will cost 5025 ms to finish job.--pool-1-thread-3
I am finish.--pool-1-thread-3
FirstValue is 5025
I am interrupted.--pool-1-thread-1
I am interrupted.--pool-1-thread-2

关于java - 如何在java中找到成功完成的第一个线程的结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70152050/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com