看一个执行完任务返回一个结果值的例子
package first;
import java.util.ArrayList;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
/**
* Runnable接口是独立的工作任务,不返回结果值。Callable接口回返回结果值。
*/
class Task implements Callable<String>{
private int id;
public Task(int id) {
this.id=id;
}
public String call() throws Exception {
return "id-->"+id;
}
}
public class Demo04 {
public static void main(String[] args) {
ExecutorService executorService=Executors.newCachedThreadPool();
ArrayList<Future<String>> list=new ArrayList<Future<String>>();
for(int i=0;i<5;i++)
//submit返回Future
list.add(executorService.submit(new Task(i)));
for (Future<String> future : list) {
try {
System.out.println(future.get());
} catch (InterruptedException | ExecutionException e) {
System.out.println(e);
return;
}finally{
executorService.shutdown();
}
}
}
}
id-->0
id-->1
id-->2
id-->3
id-->4