在给定时间后停止Java中的线程-不起作用 [英] stop a thread in java after a given time - doesn't work

查看:67
本文介绍了在给定时间后停止Java中的线程-不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个复杂的功能(优化),它有可能进入循环或仅花费过多时间,并且允许的时间由用户设置.

I have a complex function (optimisation) that can potentially enter in a loop or just to take too much time, and the time allowed is set by the user.

因此,我试图使该函数在单独的线程中运行,如果超过了最大时间,则将其停止.我使用的代码与以下代码相似,但无效,因此

Therefore I am trying to make to run the function in a separate thread, and to stop it if the maximum time is passed. I use a code similar to the one below, but it doesn't work, so

int timeMax = 2; //time in minutes  
Thread Thread_Object = new Thread_Class(... args...);
try {
  Thread_Object.start();
  Thread_Object.join(timeMax*60*1000);
}

我认为我没有正确使用"join"功能,或者它没有执行我所了解的功能.有什么主意吗?

I think that I'm not using the function "join" properly, or it doesn't do what I have understood. Any idea?

谢谢!

感谢您的回答,目前我在这里找到了一个更好的主意*.它可以工作,但仍使用不建议使用的停止"功能.新的代码是:

Thanks for the answers, currently I have found a better idea here*. It works but it still uses the function "stop" that is deprecated. The new code is:

Thread Thread_Object = new Thread_Class(... args...);

try {
  int timeMax = 1;
  Thread_Object.start();
  Thread.currentThread().sleep( timeMax * 1000 );

    if ( Thread_Object.isAlive() ) {
        Thread_Object.stop();
        Thread_Object.join();
    }

}
catch (InterruptedException e) {

}

还不确定"join"的功能,我得去看一本书.

not yet sure of the function of "join", I'll have to go to have a look at some book.

推荐答案

我建议您使用 查看全文

登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆