I would like to stop threads generated in the following manner by using jToggleButton. The threads are used for watching folders for files. I tried a lot, and searched alot,
One way would be to use a stop
method that sets a volatile boolean
to true
.
public class HelloRunnable implements Runnable {
private volatile boolean stop = false;
public void run() {
if (!stop) {
System.out.println("Hello from a thread!");
}
}
public void stop() {
stop = true;
}
public static void main(String args[]) {
for (int i = 0; i < 5; i++) {
HelloRunnable hr = new HelloRunnable();
new Thread(hr).start();
hr.stop();
}
}
}
If the thread might be blocked you can arrange to interrupt it but of course this is not guaranteed to interrupt the thread as it may not be blocked, just busy.
public class HelloRunnable implements Runnable {
private volatile boolean stop = false;
private volatile Thread thread = null;
public void run() {
thread = Thread.currentThread();
if (!stop) {
System.out.println("Hello from a thread!");
}
}
public void stop() {
stop = true;
if ( thread != null ) {
thread.interrupt();
}
}
public static void main(String args[]) {
for (int i = 0; i < 5; i++) {
HelloRunnable hr = new HelloRunnable();
new Thread(hr).start();
hr.stop();
}
}
}
This last technique should also work if using WatchService.poll(...) or WatchService.take().
It should also interrupt the thread if it is busy with most IO processes.