java - 执行器不返回 10 个 future 对象

标签 java multithreading executorservice

我有一个线程池为 10 的执行程序服务,我预计会得到 10 条打印输出语句,间隔三秒,但我只收到一条打印输出语句。我传递了 10 作为参数,因此我预计有 10 个线程正在运行。如何检索 10 个 future 对象?

public class Demo {
    private static final ExecutorService executor = Executors.newFixedThreadPool(10);

    public static void main (String[] args) throws ExecutionException, InterruptedException {

        ArrayList futureObjects = new ArrayList();

        Callable<Integer> task = () -> {
            try {
                TimeUnit.SECONDS.sleep(3);
                return 123;
            }
            catch (InterruptedException e) {
                throw new IllegalStateException("task interrupted", e);
            }
        };

        System.out.println("Before execution of threads");

        Future<Integer> future = executor.submit(task);

        Integer result = future.get();
        futureObjects.add(future.get());

        System.out.println("result: " + result);

        for(Object futures : futureObjects ){
            System.out.println("Futures in ArrayList: " + futures);
        }
    }

}

我得到的输出是:

线程执行之前

结果:1​​23

ArrayList 中的 future :123

最佳答案

您实际上只添加了一项任务并提交到线程池,因此执行并返回了一项任务。

您需要一起提交多个任务(使用下面的选项1或选项2),以便您可以实际利用线程池(保持线程繁忙)。

您可以查看以下代码的更新版本:

选项(1):ExecutorService-invokeAll():

private static final ExecutorService executor = Executors.newFixedThreadPool(10);

    public static void main (String[] args) throws ExecutionException, InterruptedException {

        ArrayList futureObjects = new ArrayList();

        Callable<Integer> task = () -> {
            try {
                TimeUnit.MILLISECONDS.sleep(100);
                return 123;
            }
            catch (InterruptedException e) {
                throw new IllegalStateException("task interrupted", e);
            }
        };

        List<Callable<Integer>> callables = new ArrayList<>();
        callables.add(task);
        callables.add(task);
        callables.add(task);
        callables.add(task);
        //Add other tasks

        System.out.println("Before execution of threads");

        List<Future<Integer>> futures = executor.invokeAll(callables);

        for(Future future : futures ){
            System.out.println("Futures in ArrayList: " + future.get());
        }
    }

选项(2):ExecutorService-submit():

private static final ExecutorService executor = Executors.newFixedThreadPool(10);

    public static void main (String[] args) throws ExecutionException, InterruptedException {

        ArrayList futureObjects = new ArrayList();

        Callable<Integer> task = () -> {
            try {
                TimeUnit.MILLISECONDS.sleep(100);
                return 123;
            }
            catch (InterruptedException e) {
                throw new IllegalStateException("task interrupted", e);
            }
        };

        List<Callable<Integer>> callables = new ArrayList<>();
        callables.add(task);
        callables.add(task);
        callables.add(task);
        callables.add(task);
        //Add other tasks

        List<Future<Integer>> futures = new ArrayList<>();
        System.out.println("Before execution of threads");

        for(Callable<Integer> callable : callables) {
            futures.add(executor.submit(callable));
        }

        for(Future future : futures ){
            System.out.println("Futures in ArrayList: " + future.get());
        }
    }

可以引用API here

关于java - 执行器不返回 10 个 future 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40433316/

相关文章:

java - executorservice 以 block 的形式从数据库中读取数据并在其上运行进程

Java在方法内部添加关闭钩子(Hook)

Java并发: Modifying latch/ThreadGroup to achieve Executor behaviour

父级和子级中的 Java this 未按预期工作

c++ - RPi2、OpenMAX、死锁

java - 将方程转化为代码

java - 意外的 VarHandle 性能(比替代方案慢 4 倍)

Java多线程等待任务结束

java - android.database.sqlite.SQLiteConstraintException : UNIQUE constraint failed:

java - 部署后 Google App Engine 返回 HTTP 响应代码 403