2

私の問題は、メソッドgetAllVendorDetails()が別のメソッドを呼び出すということgetVendordetailsById(int id)です。そのメソッドgetVendordetailsById()が指定された時間 (30 秒など) 内に応答/回答を返さなかった場合、次のベンダーに移動するか、実行をスキップしてユーザーにエラーメッセージを表示する必要があります。Javaでこの結果をどのように達成できますか。以下のコードで試しましたが、うまくいきません。中に入った後getVendordetailsById()、返されません。

パブリック クラス テスト {

public static void main(String[] args) {
    long currentTime=System.currentTimeMillis();
    Date date=new Date(currentTime);
    date.setSeconds(date.getSeconds()+30);
    long end=date.getTime();
    System.out.println("Time="+(end-currentTime));

    List<Integer> vendorId= new ArrayList<Integer>();
    for (int i = 1; i <= 100000; i++) {
        vendorId.add(i);
    }
    boolean isSuccess=false;
    boolean flag=true;

    while(end>System.currentTimeMillis()){

        if(flag){
            flag=false;
            for (int i = 0; i < vendorId.size() && end>System.currentTimeMillis() ; i++) {
                getVendordetailsById(vendorId.get(i));
                isSuccess=true;
            }
        }
        System.out.println("bye");
    }

    if(isSuccess){
        System.out.println("Success");
    }else{
        System.out.println("Errorr");
    }



    System.out.println("Current time="+System.currentTimeMillis());
}

private static void getVendordetailsById(Integer id) {
    System.out.println("vendor number="+id);
    int a=0;
    for (int i = 1; i <= 1000; i++) {
        a=a+i;
    }

    System.out.println("Current value of a="+a);
}

}

4

1 に答える 1

0

java.util.concurrent.Future を使用して問題を解決できます。

まず、java.util.concurrent.Executors を使用して、将来のジョブを送信するためのエグゼキューターを作成する必要があります。

そのような

   //suggest that use it out of the loop
   //or in the static field
   java.util.concurrent.ExecutorService es = java.util.concurrent.Executors.newFixedThreadPool(1);
   //...in the loop
   Future<Object> future = es.submit(new Callable<Object>{
       public Object call(){
           getVendordetailsById 
       }
   });
   try{
      Object result = future.get(30, TimeUnit.SECONDS);
   }cache(TimeoutException te){
     break;
   }cache(Exception te){
      //other exception handler
   }
于 2013-03-28T12:36:35.733 に答える