Advertisement
GeneralGDA

Finisher

Apr 6th, 2017
388
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.86 KB | None | 0 0
  1. public final class Latch
  2. {
  3.     private final Object monitor = new Object();
  4.    
  5.     private int counter = 0;
  6.     private boolean canStart = true;
  7.  
  8.     public boolean tryStart()
  9.     {
  10.         synchronized (monitor)
  11.         {
  12.             if (canStart)
  13.             {
  14.                 counter++;
  15.                 return true;
  16.             }
  17.  
  18.             return false;
  19.         }
  20.     }
  21.  
  22.     public void finish()
  23.     {
  24.         synchronized (monitor)
  25.         {
  26.             counter--;
  27.             if (0 == counter)
  28.             {
  29.                 monitor.notifyAll();
  30.             }
  31.         }
  32.     }
  33.  
  34.     public void waitForZero() throws InterruptedException
  35.     {
  36.         synchronized (monitor)
  37.         {
  38.             canStart = false;
  39.  
  40.             while (0 != counter)
  41.             {
  42.                 monitor.wait();
  43.             }
  44.         }
  45.     }
  46. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement