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

标签 java multithreading

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

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/

相关文章:

java - Junit-快速检查 : Generate String matching a pattern

Java 使用 TransactionManager 实现两阶段提交

python - python 中(多线程)套接字的列表/数组

java - EclipseLink:类型的指示器字段值缺少类

java - Shaperenderer 崩溃 libgdx

java - 如何在android studio项目中加载.properties文件数据

java - 使用 Thread 和 Executor 实现快速 Java 线程的这两个片段之间的区别?

c - 使用 pthreads 时无法捕获 SIGINT 信号

c++ - 使用 CreateThread() 通过引用传递

java - 下面的多线程场景会发生什么?