Simple calling program for Wait () and notify ()

Source: Internet
Author: User
Tags sleep thread

public class Road
{
public static void Main (String []args)
{
Car c=new car ();
Driver d =new Driver (c);
Passenger P =new Passenger (c);
New Thread (D). Start ();
New Thread (P). Start ();
}
}
Class car
{
Synchronized public void Sleep ()
{
try{
Wait ();
}
catch (Exception e)
{
}
}
Synchronized public void Week ()
{
Notify ();
}
}
Class Passenger implements Runnable
{
Car C;
Public passenger ()
{
}
Public passenger (car c)
{
This.c=c;
}
public void Run ()
{
while (true)
{
Thread.yield ();
try{
Thread.Sleep (3000);
}catch (interruptedexception IE)
{
}
System.out.println ("A passenger go on");
C.week ();
System.out.println ("Waiting Stop and Sleep ...");
C.sleep ();
}
}
}
Class Driver implements Runnable
{
Private car C;
Public driver ()
{
}
Public driver (car c)
{
This.c=c;
}
public void Run ()
{
while (true)
{
System.out.println ("Wait a passenger ...");
C.sleep ();
try{
Thread.Sleep (3000);
}catch (interruptedexception IE)
{
}
Thread.yield ();
try{
Thread.Sleep (100);
}catch (interruptedexception IE)
{
}
C.week ();
SYSTEM.OUT.PRINTLN ("Passenger Week and Go");
}
} }

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.