生产者消费者模式,就是说生产者在生产的时候,消费者休息,生产者停止生产了,消费者将就来消费,等消费者消费完后,消费者休息,生产者起来继续生场
我建了四个类模拟
测试类
public class Test {
public static void main(String[] args) {
Movie m = new Movie();
Watcher w = new Watcher(m);
Player p = new Player(m);
Thread t1 = new Thread(w);
Thread t2 = new Thread(p);
t1.start();
t2.start();
}
}
//导演类
public class Player implements Runnable {
private Movie m;
public Player(Movie m){
this.m = m;
}
@Override
public void run() {
for(int i =0;i<=20;i++){
if(i%2==0){
m.play("蜘蛛侠");
}else{
m.play("钢铁侠");
}
}
}
}
//观众类
public class Watcher implements Runnable {
private Movie m;
public Watcher(Movie m){
this.m = m;
}
@Override
public void run() {
for(int i=0;i<=20;i++){
m.watch();
}
}
}
//电影类
public class Movie {
private boolean flag=true;
private String pic;
public void play(String pic){
synchronized (this) {
if(!flag){
try {
this.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
this.pic=pic;
System.out.println("生产了:"+this.pic);
this.notify();
this.flag=!flag;
}
}
public void watch(){
synchronized (this) {
if(flag){
try {
this.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("在看:"+this.pic);
this.notifyAll();
this.flag=!flag;
}
}
}
|
|