Terminate Java Thread
The best way to terminate a Java thread is with a switch such as a boolean property, .e.g abort
. As soon as a condition is met, usually a timeout, you can change the value of abort to true and thus exit thread. Example:
import java.util.concurrent.*;
public class CheckResults {
private static int counter = 0;
private static int timeout = 10;
private static boolean abort = false;
public static void main(String[] args) throws InterruptedException, ExecutionException {
try {
ExecutorService service = Executors.newSingleThreadExecutor();
Future<?> result = service.submit(() -> {
for (int i = 0; i < 5000; i++) {
try {
CheckResults.counter++;
System.out.println(CheckResults.counter);
Thread.sleep(4000); //some logic to slow down and reach the timeout
if (abort == true)
return;
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
result.get(timeout, TimeUnit.SECONDS);
System.out.println("Reached!");
} catch (TimeoutException e) {
System.out.println("Not reached in time. Quitting.");
abort = true;
}
}
}
The above example makes use of Java 8's functional programming capability (Lambda expression), java.util.concurrent.Futurereturn
to exit the thread. It all works smoothly. Any other way to try to interrupt the execution of the Thread could be prone to problems.