Producer and Consumer Model

The producer produces one product, the consumer consumes one, the producer waits for the consumer to consume before producing, and the consumer waits for the producer to produce before consuming.

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

public class Box {
private int value;//used to store the produced products
//The flag of whether it can be produced, true (can be consumed, cannot be produced), false (can be produced, cannot be consumed)
private boolean avaliable = false;

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

avaliable = true;
notifyAll();//Notify all threads waiting for shared resources
this.value = value;
}

public synchronized int get(){//Consumer
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();
}
}







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

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326840238&siteId=291194637