---
title: "多线程中任务产生返回值"
author: "逍遥bxf飞雪"
date: "2016-05-22T22:30:52Z"
tags: []
categories: ["Web前端"]
slug: "untitled"
draft: false
lastmod: "2016-05-22T22:30:52Z"
id: 2299878
url: "https://bxfsoftware.iteye.com/blog/2299878"
---

Runnable是执行工作的独立任务，但是不能返回任何值，如果希望在任务完成时候有返回值，可以实现Callable接口。

```
package cn.thread;

//: concurrency/CallableDemo.java
import java.util.concurrent.*;
import java.util.*;

class TaskWithResult implements Callable<String> {
private int id;
public TaskWithResult(int id) {
  this.id = id;
}
//Callable接口中的方法
public String call() {
  return "result of TaskWithResult " + id;
}
}

public class CallableDemo {
public static void main(String[] args) {
  ExecutorService exec = Executors.newCachedThreadPool();
  ArrayList<Future<String>> results =new ArrayList<Future<String>>();
  for(int i = 0; i < 10; i++){
	  results.add(exec.submit(new TaskWithResult(i)));
  }
   
  for(Future<String> fs : results){
    try {
      // get() blocks until completion:
      System.out.println(fs.get());
    } catch(InterruptedException e) {
      System.out.println(e);
      return;
    } catch(ExecutionException e) {
      System.out.println(e);
    } finally {
      exec.shutdown();
    }
  }
}
} /* Output:
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
*///:~
```

get方法是Future类中：

Future就是对于具体的Runnable或者Callable任务的执行结果进行取消、查询是否完成、获取结果。必要时可以通过get方法获取执行结果，该方法会阻塞直到任务返回结果。

　　Future类位于java.util.concurrent包下，它是一个接口：

1

2

3

4

5

6

7

8

`public` `interface` `Future<V> {`

`boolean` `cancel(boolean` `mayInterruptIfRunning);`

`boolean` `isCancelled();`

`boolean` `isDone();`

`V get() throws` `InterruptedException, ExecutionException;`

`V get(long` `timeout, TimeUnit unit)`

`throws` `InterruptedException, ExecutionException, TimeoutException;`

`}`