有返回值的线程

在Java5之前,线程是没有返回值的,常常为了“有”返回值,破费周折,而且代码很不好写。或者干脆绕过这道坎,走别的路了。

 

现在Java终于有可返回值的任务(也可以叫做线程)了。

 

可返回值的任务必须实现Callable接口,类似的,无返回值的任务必须Runnable接口。

 

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



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


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

运行结果:


 
 
  1. 线程 2
  2. 线程 1
  3. 线程 1:hello
  4. 线程 2:hello


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值