程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> JAVA編程 >> JAVA編程入門知識 >> wait()和notify()的簡單調用程序

wait()和notify()的簡單調用程序

編輯:JAVA編程入門知識

  

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

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved