The recommended way from Oracle is Thread.interrupt()
. For example:
public void stop() {
Thread thread = runner;
runner = null;
thread.interrupt();
}
public void run() {
runner = Thread.currentThread();
while (runner != null) {
System.out.println("Stop Thread " + Thread.currentThread().getId());
}
System.out.println(" Done ");
}
It is true that sleep()
can be interrupted (which will raise an InterruptedException
), which is what the interrupt()
will do. However, afterwards the Thread
can continue doing whatever it wants after being "interrupted", so you must also check for a stop-condition of some kind. Above, we check runner != null
. But as you can see above, you don’t need a sleep()
in the worker thread.
If you don’t want to run the Thread
in a loop, or you have many different loops where the task may spin, you will have to make the stop check in each of those places.
The recommended way from Oracle is Thread.interrupt()
. For example:
public void stop() {
Thread thread = runner;
runner = null;
thread.interrupt();
}
public void run() {
runner = Thread.currentThread();
while (runner != null) {
System.out.println("Stop Thread " + Thread.currentThread().getId());
}
}
The recommended way from Oracle is Thread.interrupt()
. For example:
public void stop() {
Thread thread = runner;
runner = null;
thread.interrupt();
}
public void run() {
runner = Thread.currentThread();
while (runner != null) {
System.out.println("Stop Thread " + Thread.currentThread().getId());
}
System.out.println(" Done ");
}
It is true that sleep()
can be interrupted (which will raise an InterruptedException
), which is what the interrupt()
will do. However, afterwards the Thread
can continue doing whatever it wants after being "interrupted", so you must also check for a stop-condition of some kind. Above, we check runner != null
. But as you can see above, you don’t need a sleep()
in the worker thread.
If you don’t want to run the Thread
in a loop, or you have many different loops where the task may spin, you will have to make the stop check in each of those places.
The recommended way from Oracle is Thread.interrupt()
. For example:
public void stop() {
Thread thread = runner;
runner = null;
thread.interrupt();
}
public void run() {
runner = Thread.currentThread();
while (runner != null) {
System.out.println("Stop Thread " + Thread.currentThread().getId());
}
}