生產者消費者問題

public class ProducerConsumer {


/**
* @兩個生產者一起生產,把product放入棧中,如果滿了,等待消費者消費。
* @一個消費者消費,從棧中取,如果沒有了,等待生產者生產
*/
public static void main(String[] args) {
Stack s = new Stack();
new Thread(new Producer(s)).start();
new Thread(new Producer(s)).start();
new Thread(new Consumer(s)).start();


}


}
class Digua{
private int id;
public Digua(int id){
this.id = id;
}
public int getId(){
return id;
}
}
class Stack{
private  int count;

private  Digua[] ds;
public Stack(){
ds = new Digua[6];
}
//生產
public synchronized void push(Digua d){
while(count==ds.length){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
this.notifyAll();
System.out.println("生產者:"+d.getId());
ds[count++] = d;
}
//消費
public synchronized void pop(){
while(count==0){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
this.notifyAll();
count--;
System.out.println("消費者:"+ds[count].getId());

}
}
//生產者
class Producer implements Runnable {
private static Stack s;
public Producer(Stack s){
this.s = s;
}
public void run(){
for(int i=1;i<=3;i++){
s.push(new Digua(i));
try{
Thread.sleep((int)(Math.random()*1000));
}catch(InterruptedException e){
e.printStackTrace();
}
}
}
}
//消費者
class Consumer implements Runnable{
private static Stack s;
public Consumer(Stack s){
this.s = s;
}
public void run(){
for(int i=1;i<=12;i++){
s.pop();
try{
Thread.sleep((int)(Math.random()*1000));
}catch(InterruptedException e){
e.printStackTrace();
}
}
}
}
發佈了34 篇原創文章 · 獲贊 2 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章