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()
?