开发者

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 Th开发者_如何学JAVAread_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.

  • java scripting API - how to stop the evaluation


I suggest you use a Timer.


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


This might be useful

http://tempus-fugit.googlecode.com/svn/site/documentation/concurrency.html#Scheduled_Interruption

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜