In my program I have many threads in a working state, started in the method run or by calling other method from run. What is the method to stop these threads?
The threads are started as:
Runnable r = new Runnable() {
@Override
public void run() {
// do something...
}
};
new Thread(r,"Thread_1").start();
Another one may be like:
Runnable r = new Runnable() {
@Override
public void run() {
startThread(); // another method called
}
};
new Thread(r,"Thread_2").start();
What is the method of stopping thread_1
and thread_2
?
UPDATE
What I want is when I click on a button deactivate
3-4 threads working behind should get deactivated so that the user can again start those threads by again assigning a task.
Thread.stop()
is very dangerous, it's strongly recommended that you avoid it, for the reasons stated in the javadoc.
Try passing a message into the Runnable
, perhaps using something like this:
final AtomicBoolean terminate = new AtomicBoolean(false);
Runnable r = new Runnable() {
@Override
public void run() {
while (!terminate.get()) {
// do something...
}
}
};
new Thread(r,"Thread_1").start();
// some time later...
terminate.set(true);
You'd have to figure out a way to scope the variables to allow this to compile under your setup. Alternatively, extend Runnable
with your interface which has a cancel()
method (or whatever), which your anonymous classes have to implement, which does a similar sort of thing with the loop check flag.
interface CancellableRunnable extends Runnable {
void cancel();
}
CancellableRunnable r = new CancellableRunnable() {
private volatile terminate = false;
@Override
public void run() {
while (!terminate) {
// do something...
}
}
@Override
public void cancel() {
terminate = true;
}
}
new Thread(r,"Thread_1").start();
// some time later...
r.cancel();
Thread class has method stop()
introduced in java 1.0 and deprecated in java 1.1. This method still works and kills thread. So, you can stop all your threads if you want.
But this is very not recommended. The reason is described in javadoc of Thread.stop()
. So the best solution is to fix the implementation of your threads to make them exit correctly. But if it is not possible (e.g. if this is not your code) and you still need this very much use Thread.stop()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With