java需要关注的知识点---并发之从任务中产生返回值
程序员文章站
2022-03-23 14:56:03
...
class TaskWithResult implements Callable<String>{
private int id;
public int getId() {
return id;
}
public TaskWithResult(int id) {
super();
this.id = id;
}
public void setId(int id) {
this.id = id;
}
/**
* @param args
*/
public static void main(String[] args) {
}
@Override
public String call() throws Exception {
return "result of TaskWithResult :" + id;
}
}
public class CallableDemo {
public static void main(String[] args) {
ExecutorService es = Executors.newCachedThreadPool();
ArrayList<Future<String>> results = new ArrayList<Future<String>>();
for (int i = 0; i < 10; i++)
results.add(es.submit(new TaskWithResult(i)));
try {
for (Future<String> fs : results){
//调用get方法获取线程执行后的结果
System.out.println("result:===>" + fs.get());
// 调用isDone查看任务是否完成
System.out.println("done:" + fs.isDone());
}
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}finally {
System.out.println("1");
es.shutdown();
}
System.out.println("2");
}
}
上一篇: ES分布式环境说明
下一篇: remove是什么意思?