Java:并行处理数组,查找发生异常的位置
首先,我有一个数组,除了位置5之外,它是用0填充的,位置5是用“a”填充的(故意放在那里是为了抛出NumberFormatException)
然后我调用testMethod传递数组,数组的大小,以及将有多少可调用项
在本例中,数组的大小为10,有4个可调用项。。数组分块处理:
第一个区块是位置0和1 第二组是位置2和3 第三组是位置4和5 第四组是位置6和7 第五块是位置8和9 第六块是位置10
我需要找出NumberFormatException发生在哪个位置,或者从更一般的意义上说:我需要知道任何异常发生时的位置
所以我可以在消息“执行异常发生在位置5”中打印出来
我对使用ExcutorService/Callables很陌生,所以我不太确定如何实现这一点
如果用我目前的设置无法实现。。。有没有一种类似的方法来进行并行处理,从而使我能够找到异常发生的位置
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;
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 {
/*Fill the array with 0's, except for position 5 which is a letter and will throw number format exception*/
final String[] nums = new String[10];
for (int i = 0; i < 5; i++) {
nums[i] = "0";
}
nums[5] = "a";
for (int i = 6; i < nums.length; i++) {
nums[i] = "0";
}
testMethod(nums, 10, 4);
}
static void testMethod(String[] nums, int size, int processors) throws Exception {
mCallables.clear();
int chunk = (size / processors) == 0 ? size : size / processors;
System.out.println("Chunk size: "+chunk);
for (int low = 0; low < size; low += chunk) {
final int start = low;
final int end = Math.min(size, low + chunk);
mCallables.add(new Callable<Boolean>() {
@Override
public Boolean call() throws Exception {
System.out.println("New call");
for (int pos = start; pos < end; pos++) {
System.out.println("Pos is " + pos);
System.out.println("Num is " + nums[pos]);
double d = Double.parseDouble(nums[pos]);
} //end inner loop
return true;
} //end call method
}); //end callable anonymous class
}
try {
List<Future<Boolean>> f = mExecutor.invokeAll(mCallables);
for (int i = 0; i < f.size(); i++) {
f.get(i).get();
}
} catch (ExecutionException e) {
String s = e.toString();
System.out.println(s);
System.out.println("Execution exception"); //need to write here which pos the numberFormat exception occurred
}
mExecutor.shutdown();
}
}
# 1 楼答案
您不能在
Double.parseDouble
行上添加一个try/catch并抛出一个包含该位置的异常吗