Java Callable接口

参考文章

一 理论

Runnable是执行工作的独立任务,但是不返回任何值。如果我们希望任务完成之后有返回值,可以实现Callable接口。在JavaSE5中引入的Callable是一个具有类型参数的范型,他的类型参数方法表示为方法call()而不是run()中返回的值,并且必须使用ExecutorService.submint()方法进行调用。

二 示例

//实现接口Callable 参数类型是String
public class TaskWithResult implements Callable<String> {
    private int id;
    public TaskWithResult(int id){
        this.id=id;
    }
    @Override
    public String call() throws Exception {
        return "result of TaskWithResult "+id;
    }
}
//java测试方法,基于junit4
@Test
    public  void main2() {
        ExecutorService exec= Executors.newCachedThreadPool();
       //Future接口后面有源码
        ArrayList<Future<String>> results=new ArrayList<Future<String>>();
        long start=System.currentTimeMillis();
        for(int i=0;i<10;i++){
            results.add(exec.submit(new TaskWithResult(i)));
        }
        //System.out.println("====================cost:"+(System.currentTimeMillis()-start));
        int count=0;
      //遍历数据
        for(Future<String> fs:results){
            //System.out.println("========cost:"+(System.currentTimeMillis()-start));
            long start2=System.currentTimeMillis();
            try{
              //取数据
                System.out.println(fs.get());

            }catch (InterruptedException e){
                System.out.print(e);

            }catch (ExecutionException e){
                System.out.print(e);
            }finally {
                exec.shutdown();

            }
            //System.out.println((count++)+"====================cost:"+(System.currentTimeMillis()-start2));

        }

    }

执行结果如下图:


result.png

三Callable接口源码

@FunctionalInterface
public interface Callable<V> {
    /**
     * Computes a result, or throws an exception if unable to do so.
     *
     * @return computed result
     * @throws Exception if unable to compute a result
     */
    V call() throws Exception;
}

四 Future 接口源码

public interface Future<V> {
//取消
boolean cancel(boolean mayInterruptIfRunning);
boolean isCancelled();
//任务是否完成
boolean isDone();
//获得数据
V get() throws InterruptedException, ExecutionException;
V get(long timeout, TimeUnit unit)
        throws InterruptedException, ExecutionException, TimeoutException;
}
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 136,061评论 19 139
  • 山有木兮木有枝,心悦君兮君不知… 最可惜的是最重要的人在离开时连一张合照都没有。相信每个人都会有一段不为人知的感情...
    梦落方华阅读 3,446评论 0 0
  • 春燕啄着泥处那爱的巢窝 屋檐下何时有步态蹒跚娇羞的女子走着 走向我 指尖的温暖拂过我的片羽, 温暖煽动 ...
    张新怡阅读 1,688评论 0 4

友情链接更多精彩内容