黑马程序员技术交流社区
标题:
生产消费者模式
[打印本页]
作者:
梁小刀11
时间:
2015-2-8 15:40
标题:
生产消费者模式
package produtor_consumer;
public class APP {
public static void main(String[] args) {
movie m=new movie();
player p=new player(m);
watcher w=new watcher(m);
new Thread(p).start();
new Thread(w).start();
}
}
class movie {
private String str;
private boolean flag=true;
public synchronized void play(String str){
if(!flag){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("生产了-->"+str);
this.str=str;
this.notify();
this.flag=false;
}
public synchronized void watch(){
if(flag){
try {
this.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
try {
Thread.sleep(200);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("消费了-->"+str);
this.notify();
this.flag=true;
}
}
class player implements Runnable {
private movie m;
public player(movie m) {
super();
this.m = m;
}
@Override
public void run() {
for(int i=0;i<200;i++){
if(0==i%2){
m.play("左青龙");
}else{
m.play("右白虎");
}
}
}
}
class watcher implements Runnable {
private movie m;
public watcher(movie m) {
super();
this.m = m;
}
@Override
public void run() {
for(int i=0;i<20;i++){
m.watch();
}
}
}
复制代码
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2