生产者与消费者模式

生产者生产一个产品,消费者消费一个,生产者要等消费者消费了才可以生产,消费者要等生产者生产了才有消费。

-----------------------
package com.tangkuo.thread.producer.cn;

public class Box {
private int value;//用于存放生产 的产品
//能否生产的标志,true( 可消费,不能生产),false (可生产,不能消费)
private boolean avaliable = false;

public synchronized void put(int value){//生产者
while(avaliable == true){
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}

avaliable = true;
notifyAll();//通知所有等待共享资源的线程
this.value = value;
}

public synchronized int get(){//消费者
while(avaliable == false){
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
avaliable = false;
notifyAll();
return this.value;
}

}


-----------------------------------
package com.tangkuo.thread.producer.cn;

public class Producer extends Thread {
private Box box;
private String name;

public Producer(Box b, String n){
box = b;
name = n;
}

public void run(){
for(int i = 1; i < 6; i++){
box.put(i);
System.out.println("生产者"+ name + " 生产产品:"+i);
try {
sleep((int) (Math.random() * 100));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}


-----------------------------------------------------
package com.tangkuo.thread.producer.cn;

/**
* 消费者类
* @author Administrator
*
*/
public class Consumer extends Thread {

private Box box;
private String name;

public Consumer(Box b, String n){
box = b;
name = n;
}

public void run(){
for(int i = 1; i < 6; i++){
box.get();
System.out.println("消费者"+ name +"消费产品:"+ i);
try {
Thread.sleep((int) (Math.random() * 100));
} catch (InterruptedException e) {
e.printStackTrace();
}

}
}
}


-------------------------------------------
package com.tangkuo.thread.producer.cn;

public class ProducerConsumerTest {

public static void main(String[] args) {
Box box = new Box();
Producer p = new Producer(box, "001");
Consumer c = new Consumer(box, "002");
p.start();
c.start();
}
}







-------------------------------

猜你喜欢

转载自tangkuo.iteye.com/blog/2296576