I have walked through many existing answers about stopping a thread.I copy a typical piece of code below.
public class HelloWorld {
public static void main(String[] args) throws Exception {
Thread thread = new Thread(new Runnable() {
public void run() {
try {
while (!Thread.interrupted()) {
Thread.sleep(5000);
System.out.println("Hello World!");
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
});
thread.start();
System.out.println("press any key to quit");
System.in.read();
thread.interrupt();
}
}
But this solution need to check the interrupt status in the while loop code.If what I am doing in the run method is a sequential and single path thing So I have no chance to check the interrupt status twice.For example,I want to stop a thread that is searching all disk stuff and it takes a lot of time.
How can I stop it?
In your long running process, you have to have some points where you can say
if (!keepRunning) { break; } else { do next directory/file(); }to get out of the loop.In your straw man example, if you are searching the disk, you have points in there before you process every file and directory to include this check logic.
If you have a really long running process, like encrypting a giant file, or transfering a extremely large file, you still have the ability to embed these flag checks into the process. In this example, you would be transferring blocks of bytes, before you build each block to send you would check the flag condition. Everything has to be done in steps at some point, and you can put your flag check in before each of those steps. I can’t think of anything that doesn’t have stages or steps that is long running other than a contrived example with
.sleep()or some connection logic that waits forever for something to happen.Without an exact problem you are encountering it will be very hard to answer you question in a more specific way. Show some code that you are actually having a problem with.