0

我的程序如下所示

  1. 主程序(线程 1)
  2. 创建多个简单的 java 线程(Thead 1.1、1.2...)
  3. 在每个线程(1.1 或 1.2 ..)中,我正在做一些处理,同时调用一个有时没有响应的方法(CORBA 调用)。我想为这个方法定义计时器,线程(1.1 或 1.2 调用者)应该在那里等待,直到我得到响应或计时器过期。

我编写了以下示例程序。我不认为这是正确的方法。有没有更好的方法?在这个 prg 中,我不确定何时调用中断方法。

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

}

4

2 回答 2

1

This very much sounds like you should implement Callable. This is just an example

 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";
        }
    }
} 
于 2013-04-25T13:51:52.077 回答
0

您还可以对@Eugene 的答案进行一个小改动,也就是说,shutdownNow()ExecutorService可以只调用超时cancel(true)的,而不是调用本身。futureResult这是代码片段:

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()尝试停止当前正在执行的任务之外,还可以防止等待任务的启动。

于 2013-05-09T05:50:57.297 回答