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

后端 未结 5 541
清酒与你
清酒与你 2021-01-25 04:06

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 tryi

相关标签:
5条回答
  • 2021-01-25 04:33

    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.

    0 讨论(0)
  • 2021-01-25 04:36

    This might be useful

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

    0 讨论(0)
  • 2021-01-25 04:49

    I suggest you use a Timer.

    0 讨论(0)
  • 2021-01-25 04:49

    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

    0 讨论(0)
  • 2021-01-25 04:57

    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.

    0 讨论(0)
提交回复
热议问题