多線程之偷了個懶之經典生產消費問題

package kkk;dom


public class Jingdian {ide

public static void main(String args[]){this

Clerk cl=new Clerk();spa

Thread prt=new Thread(new Producer(cl));//生產者線程線程

Thread cot=new Thread(new Consumer(cl));//消費者線程get

prt.start();產品

cot.start();it

}io

}class

//新建另外一個類

package kkk;


public class Clerk {

private int product=0;//產品默認爲0;

public synchronized void addProduct(){//生產者生成出來的產品交給店員

if(this.product>=20){//20個最大庫存

try {

wait();//產品已滿,請稍等在生產

} catch (InterruptedException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}else{

product++;

System.out.println("生產者生產第"+product+"個產品");

notifyAll();//通知等待區的消費者今天取產品了

}

}//消費者從店員處取產品

public synchronized void getProduct(){

if(this.product<=0){

try {

wait();//產品沒有貨了,請稍等再取

} catch (InterruptedException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}else{

System.out.println("消費者取走了第"+product+"個產品");

product--;

notifyAll();//通知等待區的生成者能夠生產 產品

}

}

}

//新建消費類

package kkk;

//消費者線程要執行的任務

public class Consumer implements Runnable {

private Clerk cl;

public Consumer(Clerk cl){

this.cl=cl;

}

public void run(){

System.out.println("消費者開始取走產品");

while(true){

try{

Thread.sleep((int)(Math.random()*10)*100);

}catch(InterruptedException e){

e.printStackTrace();

}

cl.getProduct();//取走產品

}

}

}

//新建生產者類

package kkk;

//生產者線程要執行的任務

public class Producer implements Runnable {

private Clerk cl;

public Producer(Clerk cl){

this.cl=cl;

}

public void run(){

System.out.println("生產者開始生產產品!");

while(true){

try {

Thread.sleep((int)(Math.random()*10)*100);

} catch (InterruptedException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

cl.addProduct();//生產產品

}

}

}

相關文章
相關標籤/搜索