当我从学生名称archana抛出异常时。 根据我的理解 InvokeAll 等待所有任务完成,然后返回将来的列表
我得到的输出是
pool-1-thread-1 Helloprerna
pool-1-thread-2 Helloabc
HELLO SOMEERROR
Execution Completed
我希望显示其他任务输出,以便不抛出异常。任何建议
public class Executor {
public static void main(String args[]) throws InterruptedException{
ExecutorService executor=Executors.newFixedThreadPool(5);
ArrayList<Student> list = new ArrayList<Student>();
list.add(new Student("prerna"));
list.add(new Student("abc"));
list.add(new Student("archana"));
list.add(new Student("def"));
list.add(new Student("xyz"));
list.add(new Student("ritu"));
list.add(new Student("babita"));
try {
List<Future<String>> resultList=executor.invokeAll(list);
for(Future<String> f:resultList){
//if(f.isDone()){
System.out.println(f.get());
//}
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}catch (ExecutionException e) {
// TODO Auto-generated catch block
System.out.println("HELLO SOME ERROR");
//e.printStackTrace();
}
executor.shutdown();
executor.awaitTermination(10, TimeUnit.SECONDS);
System.out.println("Execution Completed");
}
}
public class Student implements Callable<String>{
String name;
public Student(String name) {
super();
this.name = name;
}
@Override
public String call() throws Exception {
// TODO Auto-generated method stub
if(name=="archana"){
throw new Exception();
}
return display(name);
}
private String display(String name2) {
try {
// System.out.println(Thread.currentThread().getName());
name2=Thread.currentThread().getName()+" Hello"+ name;
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return name2;
}
}
答案 0 :(得分:2)
你可以移动try / catch:
原件:
try {
List<Future<String>> resultList=executor.invokeAll(list);
for(Future<String> f:resultList){
try{
System.out.println(f.get());
}catch (ExecutionException e) {
System.out.println("HELLO SOME ERROR: " + e.getMessage());
}
} catch (InterruptedException e) {
e.printStackTrace();
}
将更确切地说:
EventHandler
所以在这里你将获得所有OK结果,你可以处理每项任务的异常执行。
答案 1 :(得分:0)
这种模式应该是:主线程创建并调用从属线程,它应该返回ok值或错误值(如果有任何错误)。然后主线程应该从奴隶收集结果并处理它们。