一段时间后停止申请

时间:2012-04-09 23:19:37

标签: java time

我想做一些计算,但是如果他们花了太多时间(比如10秒),我想停下来并显示当前的最佳结果。

用Java做好准备吗?我不想在每个函数中编写时间检查。

3 个答案:

答案 0 :(得分:2)

按照建议使用Timer或使用多个线程。在主程序中,启动另一个计算线程。主线程通过Thread.sleep休眠,并在超时后终止计算。

main thread +-------+---sleeping---termination----+
                    |                 |
another thread      +---calculation---+

答案 1 :(得分:1)

您可以创建一个单独的线程,您可以在计算线程的开头开始,使用Timer.sleep(int)方法在10秒后,将布尔值设置为true。然后在计算主题中if(finished) break;

答案 2 :(得分:-1)

让另一个线程的循环每秒递增一个值,然后在10秒后退出。

public class counter extends Thread, implements Runnable{
 public void run()
{
 for(int index=0; index<10; index++)//Waits ten seconds
{
this.sleep(1000);//ms
}
System.exit(0);//Closes the application
}

但主线程仍然可以执行。要取消关闭,我想你可以有一个volatile布尔值,如果及时收到输入,它将被设置为true。

相关问题