我有一个调用外部应用程序的Restful Service。此应用程序正在使我的服务挂起。因此,当用户拨打我的服务时,由于此外部应用程序可能需要一个小时。外部应用程序只需要几秒钟执行。否则,出现了问题。所以我想让我的服务中的代码执行长达30秒。如果它通过了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...
}
我已经研究过这个尝试,但没有运气。你能举个例子说明你的意思吗? –
@ChrisBolton http://www.mkyong.com/java/jdk-timer-scheduler-example/就是一个很好的例子。计时器创建自己的线程,因此您不需要。 – ajpaparo
http://stackoverflow.com/questions/10029831/how-do-you-use-a-timertask-to-run-a-thread另一个很好的例子给你。 – ajpaparo