我有一个正在调用外部应用程序的 Restful 服务。该应用程序使我的服务挂起。因此,当用户调用我的服务时,由于这个外部应用程序,可能需要一个小时。外部应用程序只需几秒钟即可执行。否则,就会出现问题。因此,我希望服务中的代码最多执行 30 秒。如果超过了 30 秒标记,我想停止该服务并重新启动它。
这就是我想要的:
public static void main(String[] args){
Thread thread = new Thread(){
public void run(){
System.out.println("Hello Thread");
}
};
thread.start();
//if thread is alive in 30 seconds, stop and retry
}
我不希望代码每 30 秒执行一次。我希望能够停止代码执行并从头开始重新启动。
这是服务:
@Path("/test")
@GET
@Produces(MediaType.APPLICATION_JSON )
public Response test(@QueryParam("input") String input) {
//call external application... if it hangs, it will take more than 30 seconds...
}
最佳答案
您正在谈论Timeout ,对吗?
我在此类中通常实现 TimeoutCmd 接口(interface)的方法是关闭您尝试读取的 InputStream。这将引发异常并释放正在等待的线程。
其他时候,如果定期检查 THread.interrupt 值,则使用 Thread.interrupt 可以有效地停止长时间运行的线程
关于java - 30 秒后停止线程并重试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31348992/