方法超时

时间:2013-04-25 12:42:17

标签: java multithreading timer

我的程序如下所示

  1. 主程序(主题1)
  2. 创建多个简单的java线程(Thead 1.1,1.2 ...)
  3. 在每个线程(1.1或1.2 ..)中,我正在做一些处理也调用一个方法 有时没有响应(CORBA调用)。我想定义计时器 这个方法和线程(1.1或1.2无论谁正在调用)应该在那里等待,直到我得到响应或计时器到期。
  4. 我写了以下示例程序。我不认为这是正确的方法。有没有更好的方法?在这个prg中,我不确定何时调用interupt方法。

    public class MethodTimeout implements Runnable{
    
    /**
     * @param args
     */
    
    public Thread t1 = null;
    public int threadnum = 0;
    public static void main(String[] args) {
    
    
        for (int i=0; i<3; i++){
            MethodTimeout mt  =new MethodTimeout();
            Thread t = new Thread(mt,"thread "+(i+1));
            mt.t1 = t;
            mt.threadnum = (i+1); 
            t.start();
        }
    
        System.out.println("stmt after execution");
    }
    
    public Object testTimeout(){
        long startTime = System.currentTimeMillis();
        try {
    
            System.out.println("in side method start "+t1.getName()+" start time"+startTime);
    
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        long endtime = System.currentTimeMillis();
        System.out.println("in side method end "+t1.getName()+" total time"+(endtime-startTime) );
        return null;
    }
    
    
    @Override
    public void run() {
    
        Thread timeout  = new Thread (){
            public void run() {
                testTimeout();
            };
        };
        timeout.start();
    
        try {
            Thread.sleep(2000);
            timeout.interrupt();
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }       
        System.out.println(t1.getName() + " is ending");
    }
    

    }

2 个答案:

答案 0 :(得分:1)

听起来你应该实现Callable。 这只是一个例子

 import java.util.concurrent.Callable;
 import java.util.concurrent.ExecutorService;
 import java.util.concurrent.Executors;
 import java.util.concurrent.Future;
 import java.util.concurrent.TimeUnit;
 import java.util.concurrent.TimeoutException;

 public class Test {    
     public static void main(String[] args) throws Exception {
         ExecutorService service = Executors.newFixedThreadPool(2);
         Future<String> futureResult = service.submit(new MyCall());
             try{
                 String result = futureResult.get(20, TimeUnit.MILLISECONDS);
             } catch(TimeoutException timeout){
                  System.out.println("Timeout");
                  service.shutdownNow();
             }
   }

   static class MyCall implements Callable<String> {
        @Override
        public String call() throws Exception {
             try{
                  //Simulate some corba work
                  Thread.sleep(1000);
             }catch(InterruptedException e){
                  Thread.currentThread().interrupt();
                  System.out.println("Shutting down the task!");
             }
                 return "The result";
        }
    }
} 

答案 1 :(得分:0)

您还可以对@ Eugene的答案进行一次小的更改,而不是在shutdownNow()上调用ExecutorService,而只需在cancel(true)上调用futureResult {1}}超时了。以下是代码段:

public class Test {    
     public static void main(String[] args) throws Exception {
         ExecutorService service = Executors.newFixedThreadPool(2);
         Future<String> futureResult = service.submit(new MyCall());
             try{
                 String result = futureResult.get(20, TimeUnit.MILLISECONDS);
             } catch(TimeoutException timeout){
                  System.out.println("Timeout");
             } finally {
                  futureResult.cancel(true);
             }
   }

这只是为了确保只取消超时线程。由于shutdownNow()除了试图停止当前正在执行的任务外,还会阻止等待任务的启动。