Java暂停进程和执行另一个流程

时间:2013-04-29 10:41:37

标签: java multithreading

我正在尝试做这件事,但没有得到怎么样?代码请求网络服务发送SMS计费信息;当计费成功或失败时,将记录网络服务的响应。         有时需要很长时间才能获得响应,我想取消/暂停该过程并使用新号码重新发送请求。

long before = System.currentTimeMillis();
String resp = new SmsConnection().doResponseRequest(sms);
long totalResponseTime=((System.currentTimeMillis() - before )/1000);

我只能记录totalResponseTime,有时需要50-100秒才能从服务获得响应。有什么方法我可以说

“如果resp超过15秒取消/暂停此请求并同时重新发送另一个请求。收到回复后,我们将处理该请求。”

我需要像TimeOut Option这样的东西来接收响应。请建议。

谢谢,

3 个答案:

答案 0 :(得分:0)

您可以通过将new SmsConnection().doResponseRequest(sms);提取到ExecutorService来使用Callable。您可以看到示例here

答案 1 :(得分:0)

使用Callable:

Future<String> futureResponse = service.submit(new YourCallable); //service is the ExecutorService that you use
//this will block for 15 seconds here
String result = futureResponse.get(15, TimeUnit.SECONDS); //this needs to wrapped in a try catch with TimeoutException
if(result == null){
    //You did not get the result in 15 seconds
    futureResponse.cancel(true);//kill this task

    //schedule a new task
    service.submit(new YouCallable());

}

答案 2 :(得分:0)

这是我的问题的简单解决方案!感谢Eugene和Dmitry提供的提示和建议!我创建了一个接收响应的方法,然后在synchronized(this){}块中调用了这个方法!!

 public String getResponse(final StsSmsSubmit sms) throws InterruptedException, ExecutionException
    {
        String response="";
       Callable<String> responsecode=new Callable<String>() {


        @Override
        public String call() throws Exception {

           final String resp = new StsSmsConnection().doRequest(sms);
           return resp;
        }
    };
       ExecutorService service=Executors.newSingleThreadExecutor();
         Future task=service.submit(responsecode);
         try{
         response=(String) task.get(30, TimeUnit.SECONDS);
    }
    catch(TimeoutException tE)
    {
       System.out.println("TimeOutException Occurred  "+tE.getMessage()+"at "+ new Date());
       log.fatal("TimeOut Exception is catched. at "+ new Date());
       response="TimeOut";
    }
         service.shutdown();


       return response;

    }
相关问题