I want to interrupt a thread after a fixed amount of time. Someone else asked the same question, and the top-voted answer (https://stackoverflow.com/a/2275596/1310503) gave the solution below, which I have slightly shortened.
import java.util.Arrays;
import java.util.concurrent.*;
public class Test {
public static void main(String[] args) throws Exception {
ExecutorService executor = Executors.newSingleThreadExecutor();
executor.invokeAll(Arrays.asList(new Task()), 2, TimeUnit.SECONDS);
executor.shutdown();
}
}
class Task implements Callable<String> {
public String call() throws Exception {
try {
System.out.println("Started..");
Thread.sleep(4000); // Just to demo a long running task of 4 seconds.
System.out.println("Finished!");
} catch (InterruptedException e) {
System.out.println("Terminated!");
}
return null;
}
}
They added:
the sleep() is not required. It is just used for SSCCE/demonstration purposes. Just do your long running task right there in place of sleep().
But if you replace Thread.sleep(4000);
with for (int i = 0; i < 5E8; i++) {}
then it doesn't compile, because the empty loop doesn't throw an InterruptedException. And for the thread to be interruptible, it needs to throw an InterruptedException.
Is there any way of making the above code work with a general long-running task instead of sleep()
?
If you want you action to be interruptable (i.e. it should be possible to interrupt it before it's completed) you need to either use other interruptable action (Thread.sleep, InputStream.read, read for more info) or manually check thread interruption status in your cycle condition using Thread.isInterrupted.
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