public class Demo06 {
public static void main(String[] args) {
//共享的街道
Street street = new Street();
//人车共享街道
new Thread(new Person(street)).start();
new Thread(new Car(street)).start();
}
}
class Street{
//信号灯
boolean flag = false;
//ns 人
public synchronized void ns(){
//如果flag为true,就是绿灯,人走
if(flag==true){
try {
Thread.sleep(1000); //等待时间1000ms = 1s
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("人走");
//信号灯改变
flag = false;
//唤醒对象等待池中的线程
this.notify();
//自己等待
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
//车走we
public synchronized void we(){
//如果flag为false,就是红灯,车走
if(flag==false){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("车走");
//信号灯改变
flag = true;
//唤醒对象等待池中的线程
this.notify();
//自己等待
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
//人线程
class Person implements Runnable{
Street street = null;
public Person(Street street) {
this.street = street;
}
@Override
public void run() {
while(true){
street.ns();
}
}
}
//车线程
class Car implements Runnable{
Street street = null;
public Car(Street street) {
this.street = street;
}
@Override
public void run() {
while(true){
street.we();
}
}
}