Java 并发:获取线程的返回值

     上一篇中Runable是独立线程,它不会存在线程返回值的问题,但是在实际项目中可能就需要返回值。下文是我看《Thinking in Java》一书时的笔记。

     为获取线程返回值,对应的线程类需要实现 Callable 接口。下面是一个示例

public class TaskWithResult implements Callable<String> {
	protected int countDown = 100000;
	private static int taskCount = 0;
	private final int id = taskCount++;
	public TaskWithResult() {}
	
	public TaskWithResult(int countDown) {
		this.countDown = countDown;
	}

	@Override
	public String call() throws Exception {
		while (countDown-- > 0) {
			Thread.yield();
		}
		
		return String.valueOf(id);
	}

}

     下面的代码是的调用示例:

private static void testCallable() {
		ExecutorService executorService = Executors.newCachedThreadPool();
		
		ArrayList<Future<String>> results = new ArrayList<Future<String>>();
		for (int i = 0; i < 10; i++) {
			results.add(executorService.submit(new TaskWithResult()));
		}

		ArrayList<Future<String>> tmpList = new ArrayList<Future<String>>();
		while (true) {
			for (Future<String> fsFuture : results) {
				try {
					if (fsFuture.isDone()) {
						// 如果线程done,就调用get函数获取返回值。
						System.out.println(fsFuture.get());
						// 并将完成的线程加入到tmplist中,便于在for循环后删除。
						tmpList.add(fsFuture);
					}
				} catch (Exception e) {
				} finally {
					executorService.shutdown();
				}
			}
			
			// 删除done的线程。
			results.removeAll(tmpList);
			tmpList.clear();
			
			// 如果所有的线程都done,就退出程序。
			if (0 == results.size()) {
				break;
			}
		}
	}

      

     Callable接口需要和Future结合使用才能获取返回值。

      ExecutorService.submit函数会返回一个Future 对象,可以调用Future.isDone函数Future是否完成。如果完成,接下来就可以调用Future.get函数获取线程返回值。


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值