Clase Thread - docencia de la ETSIT-URJC
Clase Thread - docencia de la ETSIT-URJC
Clase Thread - docencia de la ETSIT-URJC
Create successful ePaper yourself
Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.
Wait and notify<br />
Se pue<strong>de</strong>n utilizar sobre un objeto sincronizado.<br />
c<strong>la</strong>ss Or<strong>de</strong>r {<br />
private static int i = 0;<br />
private int count = i++;<br />
public Or<strong>de</strong>r() {<br />
if(count == 10) {<br />
System.out.println("Out of food, closing");<br />
System.exit(0);<br />
}<br />
}<br />
public String toString() { return "Or<strong>de</strong>r " + count; }<br />
}<br />
c<strong>la</strong>ss WaitPerson extends <strong>Thread</strong> {<br />
private Restaurant restaurant;<br />
public WaitPerson(Restaurant r) {<br />
restaurant = r;<br />
start();<br />
}<br />
public void run() {<br />
while(true) {<br />
while(restaurant.or<strong>de</strong>r == null)<br />
synchronized(this) {<br />
try {<br />
wait();<br />
} catch(InterruptedException e) {<br />
throw new RuntimeException(e);<br />
}<br />
}<br />
System.out.println(<br />
"Waitperson got " + restaurant.or<strong>de</strong>r);<br />
restaurant.or<strong>de</strong>r = null;<br />
}<br />
}<br />
}<br />
c<strong>la</strong>ss Chef extends <strong>Thread</strong> {<br />
private Restaurant restaurant;<br />
private WaitPerson waitPerson;<br />
public Chef(Restaurant r, WaitPerson w) {<br />
restaurant = r;<br />
waitPerson = w;<br />
start();<br />
}<br />
public void run() {<br />
while(true) {<br />
if(restaurant.or<strong>de</strong>r == null) {<br />
restaurant.or<strong>de</strong>r = new Or<strong>de</strong>r();<br />
System.out.print("Or<strong>de</strong>r up! ");<br />
synchronized(waitPerson) {<br />
waitPerson.notify();<br />
}<br />
}<br />
try {<br />
sleep(100);<br />
} catch(InterruptedException e) {<br />
throw new RuntimeException(e);<br />
}<br />
}<br />
}<br />
}<br />
public c<strong>la</strong>ss Restaurant {<br />
private static Test monitor = new Test();<br />
Or<strong>de</strong>r or<strong>de</strong>r; // Package access<br />
public static void main(String args[]) {<br />
Restaurant restaurant = new Restaurant();<br />
WaitPerson waitPerson = new WaitPerson(restaurant);<br />
Chef chef = new Chef(restaurant, waitPerson);<br />
}<br />
} ///:~