1 package com.knowgate.multithreating; 2 3 14 15 20 21 public final class Semaphore { 22 24 public synchronized void waitSemaphore() 25 throws InterruptedException { 26 while (counter == 0) { 27 try { 28 wait(); 29 } catch(InterruptedException ex) { 30 notify(); 35 throw new InterruptedException ("Thread was interrupted"); 36 } 37 } 38 counter -= 1; 39 } 40 41 48 public synchronized boolean waitSemaphore(long timeout) 49 throws InterruptedException { 50 if (counter == 0) { 51 long startTime = System.currentTimeMillis(); 52 do { 53 long currentTime = System.currentTimeMillis(); 54 if (currentTime - startTime >= timeout) { 55 return false; 56 } 57 try { 58 wait(timeout - currentTime + startTime); 59 } catch(InterruptedException ex) { 60 notify(); 65 throw new InterruptedException ("Thread was interrupted"); 66 } 67 } while (counter == 0); 68 } 69 counter -= 1; 70 return true; 71 } 72 73 76 public synchronized void signal() { 77 counter += 1; 78 notify(); 79 } 80 81 83 public Semaphore() { counter = 0; } 84 85 89 public Semaphore(int initValue) { 90 counter = initValue; 91 } 92 93 protected int counter; 94 } 95 96 97 | Popular Tags |