//生产者-消费者 问题
public class Pro_Cus {
public static void main(String[] args){
Container con=new Container();
Producer p=new Producer(con);
Customer c=new Customer(con);
new Thread(p).start();//各定义了两个线程,可以多个线程
new Thread(c).start();
new Thread(p).start();
new Thread(c).start();
}
}
//产品
class Product{
int id;
public Product(int id){
this.id=id;
}
public String toString(){
return ""+this.id;
}
}
//装产品容器
class Container{
Product[] num=new Product[10];
int index=0;
public synchronized void push(Product pro){
while(index==num.length){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
this.notifyAll(); //倘若只有一个消费线程则,用this.notify();
num[index]=pro;
index++;
}
public synchronized Product pop(){
while(index==0){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
this.notifyAll();//倘若只有一个生产者线程,用this.notify
index--;
return num[index];
}
}
//生产者
class Producer implements Runnable{
Container con=null;
public Producer(Container con){
this.con=con;
}
public void run(){
for(int i=0;i<20;i++){
try {
Thread.sleep(10); //10毫秒生产一个
} catch (InterruptedException e) {
e.printStackTrace();
}
con.push(new Product(i));
System.out.println("生产了产品:"+i);
}
}
}
//消费者
class Customer implements Runnable{
Container con=null;
public Customer(Container con){
this.con=con;
}
public void run(){
for(int i=0;i<20;i++){
try {
Thread.sleep((int)(Math.random()*3000));//随机小于等于3秒消费一个
//Thread.sleep(3000);//为3秒消费一个用,这种形式
} catch (InterruptedException e) {
e.printStackTrace();
}
Product pro=con.pop();
System.out.println("消费了产品:"+pro);
}
}
}