user725085
user725085

Reputation: 31

How to stop a thread if it won't stop itself?

in a java Runnable, I usually write a loop, like

while(running) {
   ......
}

Then set the running to false could make the thread stop. But if the runnable is a long process without any loop, and cannot controlled by any tags. How to make a thread stop in another thread?

Thanks

Upvotes: 3

Views: 2221

Answers (6)

David
David

Reputation: 180

From what I know there are a couple of ways.

Thread t = new Thread();
t.interrupt();
t.stop();
t.destroy();

I would not advice for the later 2 as they can cause problems if they hold a lock from a synchronized object etc.

EDIT: Typo

Upvotes: 0

weekens
weekens

Reputation: 8282

Normally, you cannot do that. Thread only stops itself, all the other options are dangerous/hacky/non-portable. If you thread is in the main loop, you send it a signal, the thread shoudl react and stop by itself (in Java it is done with interrupt mechanism).

If you thread doesn't behave like this - consider this is a bug that should be fixed ASAP.

Upvotes: 0

Jim Blackler
Jim Blackler

Reputation: 23169

I would not recommend stop() as it is deprecated, and may not even work on future JVMs.

The safest way is to stop the thread with interrupt() and have the thread make its own checks to isInterrupted() - this will require the insertion of some checks unfortunately.

http://download.oracle.com/javase/1.5.0/docs/api/java/lang/Thread.html#interrupt()

Upvotes: 0

Andreas Dolk
Andreas Dolk

Reputation: 114757

Long running processes usually do have some loops. I can't imagine a long running algorithm that is coded without..

So even if you don't have a classic outer while loop, you can still add your checks against running to the inner loops in the algorithm.

(Exception: blocking I/O, socket based tasks. But that's a different story - even if you read from a stream, there is at least one loop where you can add a stop check)

Upvotes: 0

Nirmal- thInk beYond
Nirmal- thInk beYond

Reputation: 12054

use

 yourThread.sleep(interval); 

or

  yourThread.stop();

Upvotes: 0

Peter Lawrey
Peter Lawrey

Reputation: 533442

The long process might accept Thread.interrupt() so try that first. (though unlikely)

As a last resort you can use Thread.stop(), however you should read the warnings for this method.

The only safe way to stop a thread, is to place it in a seperate process and kill the process to stop it.

Upvotes: 6

Related Questions