1. public class Semaphore {
  2. private int value;
  3.  
  4. /**
  5.   * In practice, this ArrayList would be declared as
  6.   * ArrayList<Process>.
  7.   */
  8. private ArrayList queue;
  9.  
  10. public Semaphore( int value ) {
  11. this.value = value;
  12.  
  13. /*
  14.   * In practice, this.queue would be declared with
  15.   * new ArrayList<Process>.
  16.   */
  17. this.queue = new ArrayList();
  18. }
  19.  
  20. /**
  21.   * In practice, the process parameter would be of type Process.
  22.   */
  23. public static void P( Object process ) {
  24. this.value--;
  25.  
  26. if ( this.value < 0 ) {
  27. // must have been 0 or less before the decrement
  28. queue.add( process );
  29. }
  30. }
  31.  
  32. /**
  33.   * In practice, the process parameter would be of type Process.
  34.   */
  35. public static void V( Object process ) {
  36. this.value++;
  37.  
  38. if ( this.value <= 0 ) {
  39. // must have been negative before the increment
  40. queue.remove( process );
  41. // a system call I made up
  42. System.addToReadyQueue( process );
  43. }
  44. System.dispatch(); // dispatches the next process on the ready queue
  45. }
  46.  
  47. }
  48.  
  49.  
  50.  
  51. public class Dispatcher {
  52. public static void main( String[] args ) {
  53.  
  54. Semaphore mutex = new mutex( 1 );
  55. Process p1 = new Process();
  56. Process p2 = new Process();
  57.  
  58. while ( System.notHalt() ) {
  59.  
  60. // entry section
  61. mutex.P( p1 ); // mutex.value = 0
  62. mutex.P( p2 ); // mutex.value = -1, mutex.queue = [p2]
  63.  
  64. // critical section
  65. System.dispatch(); // dispatches p1, as p2 is in mutex.queue
  66.  
  67. // exit section
  68.  
  69. /*
  70.   * mutex.value = 0, so p2 is taken off mutex.queue and
  71.   * added to System.readyQueue, and the dispatcher runs
  72.   * the next process on the ready queue, which is now p2
  73.   */
  74. mutex.V( p1 );
  75.  
  76. /*
  77.   * mutex.value = 1, so nothing happens because
  78.   * mutex.value > 0
  79.   */
  80. mutex.V( p2 );
  81. }
  82.  
  83. }
  84. }