锘??xml version="1.0" encoding="utf-8" standalone="yes"?>
]]>
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();//鍚勫畾涔変簡涓や釜綰跨▼錛屽彲浠ュ涓嚎紼?br />
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;
}
}
//瑁呬駭鍝佸鍣?br />
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();//鍊樿嫢鍙湁涓涓敓浜ц呯嚎紼嬶紝鐢╰his.notify
index--;
return num[index];
}
}
//鐢熶駭鑰?br />
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姣鐢熶駭涓涓?br />
} catch (InterruptedException e) {
e.printStackTrace();
}
con.push(new Product(i));
System.out.println("鐢熶駭浜嗕駭鍝侊細"+i);
}
}
}
//娑堣垂鑰?br />
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縐掓秷璐逛竴涓?br />
//Thread.sleep(3000);//涓?縐掓秷璐逛竴涓敤錛岃繖縐嶅艦寮?br />
} catch (InterruptedException e) {
e.printStackTrace();
}
Product pro=con.pop();
System.out.println("娑堣垂浜嗕駭鍝侊細"+pro);
}
}
}