开发者社区 问答 正文

java 多线程返回list对象

实现接口Callable,能给个例子吗?要求返回ArrayList();对象

展开
收起
蛮大人123 2016-06-07 16:30:04 2702 分享 版权
1 条回答
写回答
取消 提交回答
  • 我说我不帅他们就打我,还说我虚伪
     public class Test2 {
        public static void main(String[] args) {
            ExecutorService executor = Executors.newCachedThreadPool();
            Task task = new Task();
            Future<ArrayList> result = executor.submit(task);
            executor.shutdown();
    
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e1) {
                e1.printStackTrace();
            }
    
            System.out.println("主线程在执行任务");
    
            try {
                System.out.println("task运行结果"+result.get());
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (ExecutionException e) {
                e.printStackTrace();
            }
    
            System.out.println("所有任务执行完毕");
        }
    }
    class Task implements Callable<ArrayList>{
        @Override
        public ArrayList call() throws Exception {
            System.out.println("子线程在进行计算");
            Thread.sleep(3000);
    
            return new ArrayList();
        }
    }
    2019-07-17 19:30:27
    赞同 展开评论