从Callable的Call()返回列表

时间:2019-07-02 10:16:20

标签: java multithreading callable executor

Callable的call方法不返回列表。同样,当调试器点保持在“ return strList;”行时在call()中,它在任何时间都不会到达那里。

有人帮忙,哪里出错了。

谢谢!

  private static void getThreadNameList() {
        List<String> strList=null;
        ExecutorService executorService = Executors.newFixedThreadPool(3);
        Future<List<String>> future = executorService.submit(new MyCallables());
        try {
            strList = future.get();
        } catch (InterruptedException | ExecutionException e) { }
        for(String s:strList) {
            System.out.println(s);
        }
    }

class MyCallables implements Callable<List<String>>{

    List<String> strList=null;

    @Override
    public List<String> call() throws Exception {   
        for(int i=0;i<=10;i++) {
            strList.add(Thread.currentThread().getName());      
        }
        return strList;
    }
}

1 个答案:

答案 0 :(得分:3)

您需要在MyCallables类中初始化您的列表

public class MyCallables implements Callable<List<String>>{

    List<String> strList=new ArrayList<String>();

    @Override
    public List<String> call() throws Exception {   
        for(int i=0;i<=10;i++) {
            strList.add(Thread.currentThread().getName());      
        }
        return strList;
    }

}