Wait ()
Causes the current thread to wait before another thread calls the Notify () method or the Notifyall () method of this object.
Notify ()
Wakes up a single thread waiting on this object monitor.
Package com.icss.biz.ppt;
/**
* Thinking in Java p627
* @author XIAOHP
*
*/
public class Waittest {
public static void Main (string[] args) {
Restaurant restaurant = new Restaurant ();
Waiter waiter = new Waiter (restaurant);
Waiter.start ();
Chef Chef = new Chef (restaurant,waiter);
Chef.start ();
}
}
Class Restaurant {
Public order;
}
Class order{
private static int i=0;
private int m_count;
Public order () {
M_count = i++;
if (m_count==10) {
SYSTEM.OUT.PRINTLN ("No food, end!");
System.exit (0);
}
}
}
Class Waiter extends Thread
{
Private restaurant M_restaurant;
Public Waiter (restaurant R) {
M_restaurant = R;
}
public void Run () {
while (M_restaurant.order = = null) {
Synchronized (this) {
try {
System.out.println ("Waiter thread id=" + thread.currentthread (). GetId () + "Waiting");
Wait (); Wait for the notification to be notified before running down
M_restaurant.order = null;
System.out.println ("Waiter thread id=" + thread.currentthread (). GetId () + "receive notification, take order \ n");
catch (Exception e) {
}
}
}
}
}
Class Chef extends thread{
Private restaurant M_restaurant;
Private Waiter M_waiter;
Public Chef (Restaurant Restaurant,waiter waiter) {
M_restaurant = restaurant;
M_waiter = Waiter;
}
public void Run () {
while (true) {
if (M_restaurant.order = = null) {
M_restaurant.order = New Order ();
System.out.println ("Chef thread id=" + thread.currentthread (). GetId () + "received New Order");
Synchronized (m_waiter) {
System.out.println ("Chef thread id=" + thread.currentthread (). GetId () + "----Notice waiter fetch food");
M_waiter.notify (); Inform waiter to fetch food
}
The following code moves to the sychronized and a deadlock occurs.
try {
Thread.Sleep (1000);
catch (Exception e) {
}
}
}
}
}