1 18 package org.objectweb.perseus.concurrency.lib; 19 20 25 public class Semaphore { 26 27 private Object user; 28 private boolean checkTread; 29 private boolean reentrant = false; 30 31 public boolean on; 32 33 public Semaphore() { 34 this(true); 35 } 36 37 public Semaphore(boolean on) { 38 this(on, true); 39 } 40 public Semaphore(boolean on, boolean checkthread) { 41 this(on, checkthread, false); 42 } 43 44 public Semaphore(boolean on, boolean checkthread, boolean reentrant) { 45 this.on = on; 46 this.checkTread = checkthread; 47 this.reentrant = reentrant; 48 user = null; 49 } 50 51 public void init(boolean isOn) { 52 on = isOn; 53 if (isOn) { 54 user = null; 55 } 56 } 57 58 public boolean isActive() { 59 return on; 60 } 61 62 public boolean P() { 63 if (on) { 64 synchronized (this) { 65 if (!reentrant || this.user != Thread.currentThread()) { 66 while (user != null) { 67 try { 68 wait(); 69 } catch (InterruptedException e) { 70 } 71 } 72 this.user = Thread.currentThread(); 73 } 74 } 75 } 76 return on; 77 } 78 79 public Object getUser() { 80 return user; 81 } 82 83 public void V() { 84 if (on) { 85 synchronized (this) { 86 if (!checkTread || Thread.currentThread() == user) { 87 user = null; 88 notify(); 89 } else { 90 new RuntimeException ("Not owner expected:" + user 91 + ", found: " + Thread.currentThread()); 92 } 93 } 94 } 95 } 96 } 97 | Popular Tags |