简体   繁体   中英

stop a thread in java after a given time - doesn't work

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);
}

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

Thanks!


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) {

}

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

The join method will wait the current thread until the thread that is being joined on finishes. The join with milliseconds passed in as a parameter will wait for some amount of time, if the time elapses notify the waiting thread and return.

What you can do, is after the join completes interrupt the thread you joined on. Of course this requires your thread to be responsive to thread interruption.

我建议您使用计时器

Thread.join(milis) does not kill the thread. It just waits for the thread to end.

Java threading is cooperative: you can not stop or gracefully kill a thread without it's cooperation. One way to do it is to have an atomic flag (boolean field) that thread is checking and exiting if set.

Watchdog-Timers in Java are not a simple thing, since threading is cooperative. I remember that in one project we just used Thread.stop() although it is deprecated, but there was no elegant solution. We didn't face any issues using it, though.

A good example for a Java Watchdog implementation:

http://everything2.com/user/Pyrogenic/writeups/Watchdog+timer

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM