zoukankan      html  css  js  c++  java
  • 并发:Callabel 接口

    Callable 接口是一个具有类型参数的泛型,它的 call() 方法返回一个泛型,并且可以抛出异常。必须使用 ExecutorService#submit() 方法调用它。

     1 public class TaskWithResult implements Callable<String> {
     2 
     3     private int id;
     4 
     5     public TaskWithResult(int id) {
     6         this.id=id;
     7     }
     8 
     9     @Override
    10     public String call() throws Exception {
    11         // TODO Auto-generated method stub
    12         return "result of TaskWithResult:" + id;
    13     }
    14 
    15 }
     1 public class CallableDemo {
     2     public static void main(String[] args) {
     3         // TODO Auto-generated method stub
     4         ExecutorService exec = Executors.newCachedThreadPool();
     5         ArrayList<Future<String>> results = new ArrayList<Future<String>>();
     6         for (int i = 0; i < 10; i++)
     7             results.add(exec.submit(new TaskWithResult(i)));
     8         for (Future<String> fs : results)
     9             try {
    10                 System.out.println(fs.get());
    11             } catch (InterruptedException e) {
    12                 // TODO Auto-generated catch block
    13                 e.printStackTrace();
    14             } catch (ExecutionException e) {
    15                 // TODO Auto-generated catch block
    16                 e.printStackTrace();
    17             }finally{
    18                 exec.shutdown();
    19             }
    20     }
    21 }

    submit() 方法会返回一个 Future 对象,Future 对象把 Callable#call() 的返回值按特定进行进行参数化,调用 Future#get() 可以得到 call() 的返回结果。用 Future#isDone() 判断线程是否执行结束 ,如果直接调用 Future#get() ,get() 将会阻塞,直到结果准备就绪。

    执行结果:

    result of TaskWithResult:0
    result of TaskWithResult:1
    result of TaskWithResult:2
    result of TaskWithResult:3
    result of TaskWithResult:4
    result of TaskWithResult:5
    result of TaskWithResult:6
    result of TaskWithResult:7
    result of TaskWithResult:8
    result of TaskWithResult:9

  • 相关阅读:
    一、逻辑架构与存储引擎
    三、动态SQL
    九、装饰者模式
    二、Mapper映射文件
    八、适配器模式
    测试开发系列之Python开发mock接口(二)
    测试开发系列之Python开发mock接口(三)
    html基础
    seleniumWebdriver浏览器驱动信息汇总
    用30行代码开发一个上传、下载文件的接口
  • 原文地址:https://www.cnblogs.com/mada0/p/4713181.html
Copyright © 2011-2022 走看看