java 线程 callable

来源:互联网 发布:穿越火线开挂软件 编辑:程序博客网 时间:2024/06/15 16:20
  1. 线程类:  
  2. /** 
  3.  * 类名称:CallableTest.java 
  4.  * 类描述: 
  5.  * 作    者:why 
  6.  * 时    间:2016年11月7日 
  7.  */  
  8. public class CallableTest implements Callable<String> {  
  9.     //接收传来的值  
  10.     private String str;  
  11.     public CallableTest(String str){  
  12.         super();  
  13.         this.str = str;  
  14.     }  
  15.     @Override  
  16.     public String call() throws Exception {  
  17.         //要执行的耗时操作,为了体验效果,没调用一次,休眠1000ms  
  18.         Thread.sleep(1000);  
  19.         return str;  
  20.     }  
  21.       
  22. }  
  23.   
  24.   
  25. 调用类:  
  26. /** 
  27.  * 类名称:RunTest.java 
  28.  * 类描述: 
  29.  * 作    者:why 
  30.  * 时    间:2016年11月7日 
  31.  */  
  32. public class RunTest {  
  33.     public static void main(String[] args) {  
  34.         //创建线程池  
  35.         ExecutorService ex=Executors.newCachedThreadPool();  
  36.         List<CallableTest> taskList = new ArrayList<CallableTest>();  
  37.         long now=System.currentTimeMillis();  
  38.         taskList.add(new CallableTest("1"));  
  39.         taskList.add(new CallableTest("2"));  
  40.         taskList.add(new CallableTest("3"));  
  41.         taskList.add(new CallableTest("4"));  
  42.         try {  
  43.             //调用线程,并且接收线程返回的结果  
  44.             List<Future<String>> as =ex.invokeAll(taskList);  
  45.             for(Future<String> f:as){  
  46.                 //打印返回结果  
  47.                 System.out.println(f.get());  
  48.             }  
  49.         } catch (InterruptedException e) {  
  50.             e.printStackTrace();  
  51.         } catch (ExecutionException e) {  
  52.             e.printStackTrace();  
  53.         }  
  54.         System.out.println((System.currentTimeMillis()-now));  
  55.     }  
  56. }  
  57.   
  58.   
  59. 输出结果:  
  60. 1  
  61. 2  
  62. 3  
  63. 4  
  64. 1003(耗时)  
  65.   
  66.   
  67. 正常情况下,执行4次所用时间应给是4000ms,而并发调用,用时1003ms。  
原创粉丝点击