[英]Java: ExecutorService and Callables, unable to catch exception
I'm trying to figure out why the below code doesn't print out the stack trace of a NumberFormatException when I run it? 我试图弄清楚为什么下面的代码在运行时不打印出NumberFormatException的堆栈轨迹?
I'm not sure if it is common to use callables and ExecutorService in this way, I googled and couldn't find a solution to my problem... there may be something really obvious that I'm not seeing. 我不确定以这种方式使用callables和ExecutorService是否很常见,我在Google上搜索了一下,找不到解决我的问题的方法...可能确实有一些我看不到的东西。
import java.util.ArrayList;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class CallablesTest {
private final static ArrayList<Callable<Void>> mCallables = new ArrayList<>();
private final static ExecutorService mExecutor = Executors.newFixedThreadPool(4);
public static void main(String[] args) throws Exception{
testMethod();
}
static void testMethod() throws Exception {
mCallables.clear();
for(int i=0; i<4; i++){
mCallables.add(new Callable<Void>() {
@Override
public Void call() throws Exception {
//if (Thread.currentThread().isInterrupted()) {
// throw new InterruptedException("Interruption");
//}
System.out.println("New call");
Double.parseDouble("a");
return null;
} //end call method
}); //end callable anonymous class
}
try {
mExecutor.invokeAll(mCallables);
mExecutor.shutdown();
} catch (Exception e) {
e.printStackTrace();
}
}
}
I think I may have found the answer to my own question... if you get the future objects returned from ExecutorService.invokeAll... and then surround the Future "get" calls with a try/catch block, you can catch the exception 我想我可能已经找到了我自己问题的答案...如果您从ExecutorService.invokeAll返回了将来的对象,然后用try / catch块包围了Future的“ get”调用,则可以捕获异常
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class ThreadTest {
private final static ArrayList<Callable<Boolean>> mCallables = new ArrayList<>();
private final static ExecutorService mExecutor = Executors.newFixedThreadPool(4);
public static void main(String[] args) throws Exception{
testMethod();
}
static void testMethod() throws Exception {
mCallables.clear();
for(int i=0; i<4; i++){
mCallables.add(new Callable<Boolean>() {
@Override
public Boolean call() throws Exception {
//if (Thread.currentThread().isInterrupted()) {
// throw new InterruptedException("Interruption");
//}
System.out.println("New call");
double d = Double.parseDouble("a");
return true;
} //end call method
}); //end callable anonymous class
}
try {
List<Future<Boolean>> f= mExecutor.invokeAll(mCallables);
f.get(1).get();
f.get(2).get();
f.get(3).get();
f.get(0).get();
} catch (Exception e) {
String s = e.toString();
System.out.println(s);
}
mExecutor.shutdown();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.