fubarable

Untitled

Apr 1st, 2017
138
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.33 KB | None | 0 0
  1. import java.util.concurrent.*;
  2.  
  3. public class TestExecutor {
  4.     private static final int MAX_COUNT = 20;
  5.  
  6.     public static void main(String[] args) {
  7.         Runnable task = () -> {
  8.             int counter = 0;
  9.             while (counter < MAX_COUNT) {
  10.                 // responding to the interrupt here works
  11.                 if (Thread.currentThread().isInterrupted()) {
  12.                     System.out.println("thread interrupted -- break");
  13.                     break;
  14.                 }
  15.                 counter++;
  16.                 try {
  17.                     TimeUnit.SECONDS.sleep(1);
  18.                 } catch (InterruptedException e) {
  19.                     // or responding to the interrupt here works the same
  20.                     break;
  21.                 }
  22.                 System.out.println("counter: " + counter);
  23.             }
  24.         };
  25.        
  26.         ExecutorService executor = Executors.newFixedThreadPool(1);
  27.         executor.execute(task);
  28.         System.out.println("before shutdown");
  29.         executor.shutdown();
  30.         try {
  31.             executor.awaitTermination(5, TimeUnit.SECONDS);
  32.         } catch (InterruptedException e) {
  33.             e.printStackTrace();
  34.         }
  35.         System.out.println("after await termination");
  36.         executor.shutdownNow();
  37.         System.out.println("after shutdown now");
  38.     }
  39. }
Add Comment
Please, Sign In to add comment