消费者模式
题目简介:在一个街道上有车,有人,有红绿灯,当是绿灯时人走西北道路,当是红灯时车走南北道路
public class Demo01 {
public static void main(String[] args) {
Street street = new Street();
//人线程和车线程走在一个街道对象
Thread th1 = new Thread(new Car(street));
Thread th2 = new Thread(new Person(street));
th1.start();
th2.start();
}
}
class Street{
//红绿灯 true为绿灯false为红灯
boolean flag = false;
//人走的西北方向的路
public synchronized void ws(){
if (flag){
System.out.println("人在走");
flag = false;
}
//将当前对象的线程池中的线程唤醒
this.notify();
try {
//将当前对象的线程等待
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public synchronized void ne(){
if (!flag) {
System.out.println("车在走!");
flag = true;
}
this.notify();
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
//车线程
class Car implements Runnable{
private Street street;
//街道对象
public Car(Street street) {
this.street = street;
}
@Override
public void run() {
while (true){
street.ne();
}
}
}
//人线程
class Person implements Runnable{
private Street street;
public Person(Street street) {
this.street = street;
}
@Override
public void run() {
while (true){
street.ws();
}
}
}
上述代码为简单的消费者和生产者模式
注意notify和wait只能同步的情况下实现