2

is there anyway to kill a thread or interrupt it immediately.
Like in one of my thread, i call a method which takes time to execute (2-4 seconds). This method is in a while(boolean flag) block, so i can interrupt it from the main thread.

But the problem is, if i interrupt it; it will wait till the executing loop is finished and then on next conditional check, it will stop execution.

I want it to stop right then. Is there anyway to do this?

Space Rocker
  • 787
  • 3
  • 11
  • 25

2 Answers2

4

If you need the thread stop earlier you need to put more break points in your thread.

You can use stop() to styop it immediately, but this comes at a cost and has many possible undesirable side effects. You can use stop() safely with great care, but in reality you will find it simpler/easier/safer to put in more break points (points where you check if the thread should stop)

BTW, If you want to throw an error which won't be printed you can ThreadDeath as this can shutdown the thread silently.

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
  • is it possible to share a variable between classes. Or maybe is this idea OK if i make a boolean return type method, which is used as conditional check for my while loop in the thread and i can interrupt it from any other class? Is this a wise idea? – Space Rocker Dec 25 '10 at 17:22
  • The most obvious way to interrupt a thread is to use the Thread.interrupt() method. Many blocking operations already support this. You can test for is using Thread.interrupted() in your while loop. (Saves you having to add a field). – Peter Lawrey Dec 25 '10 at 17:41
1

No, I don't believe there is a way. There's a reason you don't want to do that.

Why are Thread.stop, Thread.suspend and Thread.resume Deprecated?

Jonathan Sternberg
  • 6,421
  • 7
  • 39
  • 58
  • 1
    is it OK to use deprecated methods? Thread.stop(); exactly servers the purpose what im looking after. My question, if the application works fine at my end, will it also work fine everywhere else? – Space Rocker Dec 25 '10 at 16:52
  • 2
    @Sara, No, it's never OK. Deprecation means they're marked for removal. They might completely remove it in future versions (or maybe just dead code), it could even be the next version. You never know. It's best that you use new methods, because it'll be a pain maintaining the code in the future. – st0le Dec 25 '10 at 17:27