如果在java中没有返回响应,如何跳过循环

时间:2013-03-28 11:31:24

标签: java

我的问题是我的方法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);
}

}

1 个答案:

答案 0 :(得分: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
   }