Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to stop a thread created by implementing runnable interface?

I have created class by implementing runnable interface and then created many threads(nearly 10) in some other class of my project.
How to stop some of those threads?

like image 248
svkvvenky Avatar asked May 17 '12 06:05

svkvvenky


People also ask

How do you stop a runnable thread?

How to stop a Thread in Java | A thread in Java program will terminate ( or move to dead state) automatically when it comes out of run() method. But if we want to stop a thread from running or runnable state, we will need to calling stop() method of Thread class.

How do you stop a thread execution directly?

3. Which of the following will directly stop the execution of a Thread? Explanation: . wait() causes the current thread to wait until another thread invokes the notify() method or the notifyAll() method for this object.

What are the 2 methods by which we may stop threads?

There are two ways through which you can stop a thread in java. One is using boolean variable and second one is using interrupt() method.

How do I stop a method in Java?

To stop executing java code just use this command: System. exit(1);


1 Answers

The simplest way is to interrupt() it, which will cause Thread.currentThread().isInterrupted() to return true, and may also throw an InterruptedException under certain circumstances where the Thread is waiting, for example Thread.sleep(), otherThread.join(), object.wait() etc.

Inside the run() method you would need catch that exception and/or regularly check the Thread.currentThread().isInterrupted() value and do something (for example, break out).

Note: Although Thread.interrupted() seems the same as isInterrupted(), it has a nasty side effect: Calling interrupted() clears the interrupted flag, whereas calling isInterrupted() does not.

Other non-interrupting methods involve the use of "stop" (volatile) flags that the running Thread monitors.

like image 154
Bohemian Avatar answered Sep 21 '22 20:09

Bohemian