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

                Appendix 9 Multithreading 799
 /***************************************************************
*
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;
//************************************************************
public Encounter(Prey prey, Predator predator)
{
this.prey = prey;
this.predator = predator;
prey.setEncounter(this);
predator.setEncounter(this);
EVENTS = predator.DELAY.length;
// end constructor
       Apago PDF Enhancer
//************************************************************
}
public int beApart()
{
// prey has access, so go apart
number++;
System.out.println(Thread.currentThread().getName() +
" start beApart " + number);
return number;
// end beApart
//************************************************************
  }
 }
// end Encounter class
public int beTogether()
{
}
// predator has access, so come together
System.out.println(Thread.currentThread().getName() +
" finish beTogether " + number);
return number;
// end beTogether
WARNING!
This implementation does not work!
Figure A9.4 Inadequate implementation of Encounter class
Because the prey and predator threads run in parallel but only the predator thread contains delays, they do not interleave properly. The prey thread finishes quickly, whereas even the first output of the predator method is delayed until much later.















































   831   832   833   834   835