Page 837 - Introduction to Programming with Java: A Problem Solving Approach
P. 837

                Appendix 9 Multithreading 803 predatorHasAccess semaphore in Figure A9.5a to true, so in Figure A9.5b the predator thread
execution jumps over beTogether’s while loop and prints the output: predator finish beTogether 0
Then the execution changes the predatorHasAccess semaphore to false, calls notifyAll, and returns. Back in the run method of Figure A9.3, the predator thread enters the second iteration of the for loop and goes to sleep again in its second time delay.
Meanwhile, the previous predator thread’s notifyAll call re-activates the waiting prey thread and allows it to continue with the while loop in the beApart method in Figure A9.5b. This time, when execution returns to the while condition, it finds that the predatorHasAccess semaphore value is false. This allows it to escape from the while loop and print the output:
prey start beApart 1
Then, as before, it changes the predatorHasAccess semaphore to true, calls notifyAll, and returns.
This alternation between being apart and being together continues until (in the run method of FigureA9.2)number == encounter.EVENTS - 1,whichterminatesthepreythread.Alittlelater (in the run method of Figure A9.3) i == DELAY.length, which terminates the predator thread. Using the corrected version of the Encounter class that appears in Figures A9.5a and A9.5b, the program output looks like this:
Output:
          Apago PDF Enhancer
prey start beApart 0
predator finish beTogether 0
prey start beApart 1
predator finish beTogether 1
prey start beApart 2
predator finish beTogether 2
prey start beApart 3
prey run finished.
predator finish beTogether 3
predator run finished.
We encourage you to run this program yourself to get a physical sense of the interaction between the time- delay and wait operations.
 














































































   835   836   837   838   839