Advertisement
Guest User

Untitled

a guest
Mar 21st, 2019
83
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.61 KB | None | 0 0
  1. package coe628.lab8;
  2.  
  3.  
  4. /**
  5. * A <code>Semaphore</code> object implements a semaphore (invented by Edsger
  6. * Dijkstra).
  7. * <p>
  8. * A semaphore controls access to resources. The number of resources currently
  9. * available is the Semaphore <em>value</em>.
  10. * </p>
  11. *
  12. * @see <a href="http://en.wikipedia.org/wiki/Semaphore_(programming)">wikipedia
  13. * article</a>
  14. * @author Jared Bigelow
  15. */
  16. public class Semaphore {
  17.  
  18. private int value;
  19.  
  20. /**
  21. * Create a semaphore.
  22. * @param value The initial value of the Semaphore ( must be &ge; 0).
  23. */
  24. public Semaphore(int value) {
  25. this.value = value;
  26. }
  27. /**
  28. * Increment the number of available resources. This method never blocks.
  29. * It may wakeup a Thread waiting for the Semaphore. Dijkstra called this
  30. * the <em>V</em> operation. Many also call it <em>signal</em> or
  31. * <em>release</em>.
  32. */
  33. public synchronized void up() {
  34. value = value+1;
  35. if(value <= 0){
  36. notify();
  37. }
  38. }
  39.  
  40. /**
  41. * Request a resource. If no resources are available, the calling Thread
  42. * block until a resource controlled by the Semaphore becomes available.
  43. * Dijkstra called this
  44. * the <em>P</em> operation. Many also call it <em>wait</em> or
  45. * <em>acquire</em>.
  46. */
  47. public synchronized void down() {
  48. value=value-1;
  49. if(value <0){
  50. try{
  51. wait();
  52. }catch(InterruptedException ex) {
  53. System.out.println("Should not get here!" + ex);
  54. }
  55. }
  56.  
  57. }
  58. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement