Java 并发 - 任何人都可以帮助我输出。为什么列表是空的?

Java Concurrency - Can any one help me with the output . Why list is empty?

创建了 2 个在列表中插入值的任务。

然后使用执行器服务执行这些任务。

最后尝试找出这些列表中的值。

为什么一旦执行程序服务关闭,值就不会插入到列表中?

无法找出此行为背后的原因,谁能解释一下。

package com.executors;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.atomic.AtomicInteger;

public class ExecutorTesting {

public static AtomicInteger counter = new AtomicInteger(0);
static List<employee> list = new ArrayList<employee>();

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

    list = Collections.synchronizedList(list);

    Callable<List<employee>> c1 = new Callable<List<employee>>() {

        @Override
        public List<employee> call() throws Exception {
            for (int i = 0; i < 10; i++) {
                list.add(new employee("varun", ExecutorTesting.counter.incrementAndGet()));
            }
            return list;
        }
    };

    Callable<List<employee>> c2 = new Callable<List<employee>>() {

        @Override
        public List<employee> call() throws Exception {
            for (int i = 0; i < 10; i++) {
                list.add(new employee("varun", ExecutorTesting.counter.incrementAndGet()));
            }
            return list;
        }
    };

    ExecutorService es = Executors.newFixedThreadPool(2);

    try {
        Future<List<employee>> ef1 = es.submit(c1);
        Future<List<employee>> ef2 = es.submit(c2);

        if (ef1.isDone()) {
            System.out.println("first value : " + ef1.get());
        }
        if (ef2.isDone()) {
            System.out.println("first value : " + ef2.get());
        }

        System.out.println(list);

    } finally {
        es.shutdown();
    }

}

}

class employee {
String name;
int id;

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public int getId() {
    return id;
}

public void setId(int id) {
    this.id = id;
}

public employee(String name, int id) {
    super();
    this.name = name;
    this.id = id;
}

public String toString() {
    return this.name + " : " + this.id;
}

}

您在将其提交给 ExecuterService 后立即调用 future.isDone()。在大多数情况下,执行还没有开始,更不用说结束了。所以 isDone 都调用了 return false,你就完成了整个事情。

我不确定你面临的具体情况,但要解决这个特定测试代码中的问题,你只需要在每个 Future 上调用 get:

System.out.println("first value : " + ef1.get(10, TimeUnit.SECONDS));
System.out.println("first value : " + ef2.get(10, TimeUnit.SECONDS));

我留下了你的输出文本的复制粘贴错误;-)