Page 836 - Introduction to Programming with Java: A Problem Solving Approach
P. 836
802 Appendix 9 Multithreading
}
// end Encounter class
//************************************************************
public synchronized int beApart()
{
}
// end beApart
while (predatorHasAccess)
{
}
try
{
}
wait(); // Prey thread waits here until notified
catch (Exception e) { }
// prey has access, so go apart
number++;
System.out.println(Thread.currentThread().getName() +
" start beApart " + number);
predatorHasAccess = true;
notifyAll();
return number;
//************************************************************
}
// end beTogether
synchronizeAd pinat gbeoTogePthDeFr() Enhancer while (!predatorHasAccess)
{
public
{
}
try
{
}
wait(); // Predator thread waits here until notified
catch (Exception e) { }
// predator has access, so come together
System.out.println(Thread.currentThread().getName() +
" finish beTogether " + number);
predatorHasAccess = false;
notifyAll();
return number;
Figure A9.5b Corrected version of the Encounter class—Part B
Meanwhile (as soon as it is started), the predator thread begins running in parallel with the prey thread. When in Figure A9.3 the predator thread first calls its sleep method, it stops execution for 2.347 seconds. During most of this time delay, both threads are blocked, and neither is executing. When the 2.347-second time delay expires, the predator thread automatically wakes up, jumps over the catch, and calls encounter.beTogether. Long before this time, the prey thread changed the