【发布时间】:2013-04-25 12:42:16
【问题描述】:
我的程序如下所示
- 主程序(线程 1)
- 创建多个简单的 java 线程(Thead 1.1、1.2...)
- 在每个线程(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");
}
}
【问题讨论】:
-
这个问题也可能为您提供一个可行的解决方案:stackoverflow.com/questions/2758612/…
标签: java multithreading timer