有返回值的线程

在Java5之前,线程是没有返回值的,常常为了“有”返回值,破费周折,而且代码很不好写。或者干脆绕过这道坎,走别的路了。
 
现在Java终于有可返回值的任务(也可以叫做线程)了。
 
可返回值的任务必须实现Callable接口,类似的,无返回值的任务必须Runnable接口。
 

执行Callable任务后,可以获取一个Future的对象,在该对象上调用get就可以获取到Callable任务返回的Object了。


[java]  view plain  copy
  1. package net.spring.utils;  
  2.   
  3. import java.util.concurrent.Callable;  
  4.   
  5. public class CallableThread implements Callable<String> {  
  6.     private String str;  
  7.   
  8.     public CallableThread(String str) {  
  9.         this.str = str;  
  10.     }  
  11.   
  12.     // 需要实现Callable的Call方法  
  13.     public String call() throws Exception {  
  14.         if("线程1".equals(str)){  
  15.             Thread.sleep(1000);  
  16.         }  
  17.           
  18.         String rStr = str + ":hello";  
  19.         System.out.println(str);  
  20.         return rStr;  
  21.     }  
  22. }  

[java]  view plain  copy
  1. package net.spring.utils;  
  2.   
  3. import java.util.concurrent.Callable;  
  4. import java.util.concurrent.ExecutionException;  
  5. import java.util.concurrent.ExecutorService;  
  6. import java.util.concurrent.Executors;  
  7. import java.util.concurrent.Future;  
  8.   
  9. public class CallableTest {  
  10.   
  11.     /** 
  12.      * @param args 
  13.      * @throws ExecutionException 
  14.      * @throws InterruptedException 
  15.      */  
  16.     public static void main(String[] args) throws InterruptedException,  
  17.             ExecutionException {  
  18.   
  19.         // 线程池  
  20.         ExecutorService pool = Executors.newFixedThreadPool(10);  
  21.   
  22.         Callable<String> c1 = new CallableThread("线程1");  
  23.         Callable<String> c2 = new CallableThread("线程2");  
  24.   
  25.         // 表示异步计算的结果  
  26.         Future<String> f1 = pool.submit(c1);  
  27.         Future<String> f2 = pool.submit(c2);  
  28.   
  29.         //这里要等线程1运行完,f1.get()得到值后,才会走System.out.println(f2.get());  
  30.         System.out.println(f1.get());  
  31.         System.out.println(f2.get());  
  32.   
  33.         // 关闭线程池  
  34.         pool.shutdown();  
  35.   
  36.     }  
  37.   
  38. }  

运行结果:

[java]  view plain  copy
  1. 线程2  
  2. 线程1  
  3. 线程1:hello  
  4. 线程2:hello  

猜你喜欢

转载自blog.csdn.net/x_san3/article/details/80188465
今日推荐