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

                796 Appendix 9 Multithreading
 /*************************************************************
*
Prey.java
Dean & Dean
This models prey (producers), who avoid encounters.
*************************************************************/
*
*
*
public class Prey extends Thread
{
}
// end Prey class
private Encounter encounter;
//**********************************************************
public Prey()
{
super ("prey");
} // end constructor
//**********************************************************
public void setEncounter(Encounter encounter)
{
this.encounter = encounter;
} // end setEncounAteprago PDF Enhancer //**********************************************************
public void run()
{
}
// end run
int number;
do
{
number = encounter.beApart();
} while (number < encounter.EVENTS - 1);
System.out.println(getName() + " run finished. ");
Figure A9.2 Class describing prey (producers) who want to escape from predators This is driven by the class in Figure A9.1.
objects of the class. That’s sufficient for our example, because our driver creates only one such object, but you could also provide a one-parameter constructor to assign different names to different thread instances. The public setEncounter method allows the outside world to set the encounter reference at any time after Prey thread instantiation. The run method is the heart of a thread’s definition. In this case, it’s pretty simple. What prey want is to “be apart,” so the run method calls the relationship’s beApart method.






























































   828   829   830   831   832