Java实现生产者消费者
<span style="font-size:18px;">package com.clark.thread;
public class ManTou {
public int order;
public ManTou(int order){
this.order = order;
}
@Override
public String toString() {
return "ManTou:"+this.order;
}
}
</span>
<span style="font-size:18px;">package com.clark.thread;
//共享栈空间
public class StackBasket {
public ManTou[] mt = new ManTou[10];
int index = 0;
//生产馒头
public synchronized void push(ManTou m){
try {
while(index == mt.length){
System.out.println("生产满了!!!!!!!");
this.wait();
}
this.notify();
} catch (InterruptedException e) {
e.printStackTrace();
}
mt[index]=m;
index++;
System.out.println("生产了:" + m + " 共" + index + "个馒头");
}
//消费馒头
public synchronized ManTou pop(){
try {
while(index == 0){
System.out.println("消费完了,请等待!!!!");
this.wait();
}
this.notify();
} catch (Exception e) {
}
index--;
System.out.println("消费了:---------" + mt[index] + " 共" + index + "个馒头");
return mt[index];
}
}
</span>
<span style="font-size:18px;">package com.clark.thread;
//生产者
public class Producer implements Runnable{
StackBasket sb = new StackBasket();
public Producer(StackBasket sb){
this.sb = sb;
}
@Override
public void run() {
for (int i = 0; i <8; i++) {
ManTou m = new ManTou(i);
sb.push(m);
try {
Thread.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
</span>
<span style="font-size:18px;">package com.clark.thread;
public class Consumer implements Runnable{
StackBasket sb = new StackBasket();
public Consumer(StackBasket sb){
this.sb = sb;
}
@Override
public void run() {
for (int i = 0; i <8; i++) {
ManTou m = sb.pop();
try {
Thread.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
</span>
<span style="font-size:18px;">package com.clark.thread;
public class Test {
public static void main(String[] args) {
StackBasket sb = new StackBasket();
Producer p = new Producer(sb);
Consumer c = new Consumer(sb);
Thread t1 = new Thread(p);
Thread t2 = new Thread(c);
t1.start();
t2.start();
}
}</span>