Page 835 - Introduction to Programming with Java: A Problem Solving Approach
P. 835
Figure A9.5a Corrected version of the Encounter class—Part A
statement4, and this blocks the execution of the calling thread at that point in its execution. That thread stays in this blocked state until it receives a “wake-up” system call initiated by another thread’s execution of the notifyAll method, at which time it starts running again—from the place where it was blocked. If the program is written correctly, the condition in the while loop of exactly one of the synchronized methods is false. When this particular method is called, flow jumps over the while loop to the subsequent execut- able code.
For example, when in Figure A9.2 the prey thread first calls encounter.beApart, Figure A9.5a’s predatorHasAccess semaphore is false. So in the beApart method in Figure A9.5b, prey thread execution jumps over the while loop and prints the output:
prey start beApart 0
Then the execution changes the predatorHasAccess semaphore to true, calls notifyAll, and re- turns. The next time the prey thread calls encounter.beApart, the true value of the while condi- tion causes execution of the wait statement, and this blocks the prey thread at that point.
4 The wait method is inherited by all objects from the Object class, and it throws an InterruptedException (just like the sleep method) if the waiting thread is interrupted while it’s waiting. We must put the wait call in a try block because (as indicated previously) the exception it might throw is a checked exception, even though we never create the condition that throws that exception.
Appendix 9 Multithreading 801
/***************************************************************
*
Encounter.java
Dean & Dean
This describes predator/prey (consumer/producer) interaction.
***************************************************************/
*
*
*
public class Encounter
{
public final int EVENTS;
private int number = -1;
private Prey prey;
private Predator predator;
private boolean predatorHasAccess = false; // access semaphore
//************************************************************
public Encounter(Prey prey, Predator predator)
{
}
this.prey = prey;
this.predator = predator;
prey.setEncounter(this);
predator.setEncounter(this);
EVENTS = preAdpataorg.DoELAYP.lDenFgth;Enhancer // end constructor