Wait and notify

Source: Internet
Author: User
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) {
}
}

}
}
}






Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.