Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.concurrent.*;
- public class TestExecutor {
- private static final int MAX_COUNT = 20;
- public static void main(String[] args) {
- Runnable task = () -> {
- int counter = 0;
- while (counter < MAX_COUNT) {
- // responding to the interrupt here works
- if (Thread.currentThread().isInterrupted()) {
- System.out.println("thread interrupted -- break");
- break;
- }
- counter++;
- try {
- TimeUnit.SECONDS.sleep(1);
- } catch (InterruptedException e) {
- // or responding to the interrupt here works the same
- break;
- }
- System.out.println("counter: " + counter);
- }
- };
- ExecutorService executor = Executors.newFixedThreadPool(1);
- executor.execute(task);
- System.out.println("before shutdown");
- executor.shutdown();
- try {
- executor.awaitTermination(5, TimeUnit.SECONDS);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- System.out.println("after await termination");
- executor.shutdownNow();
- System.out.println("after shutdown now");
- }
- }
Add Comment
Please, Sign In to add comment