Timer
我更喜欢使用and来完成所有时基任务TimerTask
。检查以下代码,这可能对您有用:
Timer t =new Timer();
t.schedule(new TimerTask() {
@Override
public void run() {
//The task you want to perform after the timeout period
}
}, TIMEOUT);
编辑
我正在尝试解决您的问题。我正在使用@amicngh 编写的代码作为我的基本代码,并对其进行了一些修改。我想在TIMEOUT
你想关闭正在运行的线程之后。检查以下代码是否正常运行以及以下说明:
public class ThreadTest {
public static void main(String[] args) throws InterruptedException {
final long TIMEOUT=100;
final long startJoin = System.currentTimeMillis();
Thread runner = new Thread(new Runnable() {
long stopJoin;
@Override
public void run() {
try{
for(;;){
System.out.println("running ");
stopJoin = System.currentTimeMillis();
if ((stopJoin - startJoin) >= TIMEOUT){
throw new Exception();
}
}
}
catch (Exception e) {
// TODO: handle exception
}
}
// some actions here
});
runner.start();
synchronized (ThreadTest.class) {
ThreadTest.class.wait(TIMEOUT);
}
/*if ((stopJoin - startJoin) >= TIMEOUT)
try {
throw new Exception("Timeout when reading the response from process");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}*/
System.out.println("Running Thread");
}
}
Thread API 描述说它是不安全的destroy
or stop
(因此这两种方法都已被弃用)并且停止线程的方法之一是抛出异常。因此,我正在检查runner
线程内的超时。现在关于让主线程等待它是由synchronized
用于同步对线程的访问的 2 行代码完成的。
希望这段代码和解释能解决你的问题。