Advertisement
myshkin1

Untitled

Apr 20th, 2019
134
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.25 KB | None | 0 0
  1. import java.util.concurrent.*;
  2.  
  3. class LionPenManager {
  4.     private void removeAnimals() {
  5.         System.out.println("Removing animals");
  6.     }
  7.  
  8.     private void cleanPen() {
  9.         System.out.println("Cleaning the pen");
  10.     }
  11.  
  12.     private void addAnimals() {
  13.         System.out.println("Adding animals");
  14.     }
  15.  
  16.     public void performTask(CyclicBarrier c1, CyclicBarrier c2) {
  17.         try {
  18.             removeAnimals();
  19.             c1.await();
  20.             cleanPen();
  21.             c2.await();
  22.             addAnimals();
  23.         } catch (InterruptedException | BrokenBarrierException e) {
  24.             // Handle checked exceptions here
  25.         }
  26.     }
  27.  
  28.     public static void main(String[] args) {
  29.         ExecutorService service = null;
  30.         try {
  31.             service = Executors.newFixedThreadPool(4);
  32.             LionPenManager manager = new LionPenManager();
  33.             CyclicBarrier c1 = new CyclicBarrier(4);
  34.             CyclicBarrier c2 = new CyclicBarrier(4,
  35.                     () -> System.out.println("*** Pen Cleaned!"));
  36.             for (int i = 0; i < 4; i++)
  37.                 service.submit(() -> manager.performTask(c1, c2));
  38.         } finally {
  39.             if (service != null) service.shutdown();
  40.         }
  41.     }
  42. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement