2016-04-19 5 views
0

まず、位置5を除いて0で満たされた配列があります。これは "a"(意図的にNumberFormatExceptionをスローする)です。Java:並列で配列を処理し、例外が発生した位置を見つける

そして、私は、配列、配列のサイズ、そしていくつのCallableがあるかを渡すtestMethodを呼び出します。

この例では、アレイ10のサイズを有し、そして4つの呼び出し可能である..アレイはチャンクで処理される:

最初のチャンクが0及び1 第チャンクが位置2と3 第である位置でありますチャンクは、位置10 IはNumberFormatExceptionがが発生し、またはより一般的な意味でどの位置を見つけるために必要

位置4及び5 四チャンクが位置6,7 五チャンクが位置8,9 六チャンクであるです。例外が発生したときの位置を知る必要があります。

だから私は「実行例外が位置5で発生しました」のメッセージに

をプリントアウトすることができます私はExceutorService /呼び出し可能オブジェクトを使用することにはかなり新しいですので、私はこれを達成するためにどのように非常にわからないんだけど...

現在の設定を使用することができない場合は、この並列処理を行う同様の方法があります。例外処理が発生した位置を見つけることもできますか?

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(); 
    } 
} 

答えて

0

Double.parseDouble行にtry/catchを追加できず、その位置を含む例外をスローできませんか?

+0

はいそうです。そのような明白なことは考えていませんでした。なぜなら、私は何とか私の頭の中で呼び出し可能な例外を投げることができなかったからです。 – HollowBastion

関連する問題