public class guancheng {
//生产者消费者模式,主要是用来借助一个缓冲区,管程法.
public static void main(String[] args) {
huanchong hc =new huanchong();
new shengchan(hc).start();
new xiaofei(hc).start();
}
}
class shengchan extends Thread{
huanchong hc;
public shengchan(huanchong hc) {
this.hc =hc;
}
public void run() {
for(int i=0; i<10; i++) {
System.out.println("生产了"+i+"个馒头");
hc.push(new mantou(i));
}
}
}
class xiaofei extends Thread{
huanchong hc;
public xiaofei(huanchong hc) {
this.hc =hc;
}
public void run() {
for(int i=0; i<100; i++) {
System.out.println("消费了"+hc.pop().id+"个馒头");
}
}
}
class huanchong{
mantou[] mt =new mantou[10];
int count=0;
//存取
public synchronized void push(mantou m) {
if(count==mt.length) {
try {
this.wait();
} catch (InterruptedException e) {
}
}
mt[count++]=m;
//有了空间之后。通知消费者消费
this.notifyAll();
}
//消费
public synchronized mantou pop() {
if(count==0) {
try {
this.wait();
} catch (InterruptedException e) {
}
}
count--;
mantou m=mt[count];
//没有空间,通知生产者生产
this.notifyAll();
return m;
}
}
class mantou{
int id;
public mantou(int id) {
this.id=id;
}
}
管程法
猜你喜欢
转载自blog.csdn.net/richpersion/article/details/105125712
今日推荐
周排行