码迷,mamicode.com
首页 > 其他好文 > 详细

Callable 使用

时间:2018-05-27 17:16:48      阅读:279      评论:0      收藏:0      [点我收藏+]

标签:private   数据   使用   submit   result   ring   call()   mit   task   

# Callable 使用

一、问题

继承 Thread 类或者实现 Runnable 接口,run()方法返回类型是void,即启动的线程任务无返回结果。

二、解决

  1. 实现 Callable 接口

    public class TaskWithResult implements Callable<String> {
    
        private int id;
    
        public TaskWithResult(int id) {
            this.id = id;
        }
    
        public String call() {
            return "result of TaskWithResult " + id;
        }
    }

    ps:Callable<String>String是线程任务返回结果的数据类型,与call()方法返回类型对应。

  2. 执行线程任务

    ExecutorService exec = Executors.newCachedThreadPool();
    ArrayList<Future<String>> results = new ArrayList<Future<String>>();
    for (int i = 0; i < 10; i++) {
        // ExecutorService.submit()产生Future对象
        results.add(exec.submit(new TaskWithResult(i)));
    }
  3. Future对象

    • isDone(),判断任务是否执行完成。
    • get(),获取任务执行结果,任务未完成则阻塞。

Callable 使用

标签:private   数据   使用   submit   result   ring   call()   mit   task   

原文地址:https://www.cnblogs.com/wscy/p/9096509.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!