服务热线:13616026886

技术文档 欢迎使用技术文档,我们为你提供从新手到专业开发者的所有资源,你也可以通过它日益精进

位置:首页 > 技术文档 > JAVA > 新手入门 > 基础入门 > 查看文档

实现wait()和notify()的调度功能

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 ");

}
} } 

扫描关注微信公众号