首页 > 代码库 > java生产者消费者模型
java生产者消费者模型
import java.util.Queue;
import java.util.concurrent.LinkedBlockingQueue;
public class Consumer extends Thread {
private String product;
private Queue<String> storeHouse = new LinkedBlockingQueue<String>();
public Consumer(){
}
public Consumer(Queue<String> storeHouse){
this.storeHouse = storeHouse;
}
public void consume(){
while (true) {
synchronized (storeHouse) {
try {
while (storeHouse.isEmpty()) {
System.out.println("storeHouse is empty , please wait");
storeHouse.wait();
}
}catch (InterruptedException ie){
}
}
product = storeHouse.poll();
System.out.println("Consume :"+product);
}
}
public void run() {
consume();
}
}
import java.util.Queue;
import java.util.Random;
import java.util.concurrent.LinkedBlockingQueue;
public class Producer extends Thread {
private String product;
private Queue<String> storeHouse = new LinkedBlockingQueue<String>();
public Producer(){
}
public Producer(Queue<String> storeHouse){
this.storeHouse = storeHouse;
}
public String getProduct() {
return product;
}
public void setProduct(String product) {
this.product = product;
}
@Override
public void run(){
produce();
}
public void produce(){
while (true) {
synchronized (storeHouse) {
setProduct(getRandomString(5)) ;
storeHouse.add(product);
System.out.println("Produce : "+getProduct());
try {
storeHouse.notifyAll();
Thread.sleep(10);
}catch (InterruptedException e){
return ;
}
}
}
}
public static String getRandomString(int length){
String str="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
Random random = new Random();
StringBuffer stringBuffer = new StringBuffer();
for(int i = 0 ; i < length; ++i){
int number = random.nextInt(62);//[0,62)
stringBuffer.append(str.charAt(number));
}
return stringBuffer.toString();
}
}
import java.util.Queue;
import java.util.concurrent.LinkedBlockingQueue;
public class ProducerConsumer {
private int MAX = 10;
public ProducerConsumer() {
}
public static void main(String[] args) {
Queue<String> storeHouse = new LinkedBlockingQueue<String>();
Producer producer1 = new Producer(storeHouse);
Producer producer2 = new Producer(storeHouse);
Producer producer3 = new Producer(storeHouse);
Consumer comsumer1 = new Consumer(storeHouse);
Consumer comsumer2 = new Consumer(storeHouse);
Consumer comsumer3 = new Consumer(storeHouse);
Consumer comsumer4 = new Consumer(storeHouse);
Thread p1 = new Thread(producer1);
Thread p2 = new Thread(producer2);
Thread p3 = new Thread(producer3);
Thread c1 = new Thread(comsumer1);
Thread c2 = new Thread(comsumer2);
Thread c3 = new Thread(comsumer3);
Thread c4 = new Thread(comsumer4);
p1.start();
p2.start();
p3.start();
c1.start();
c2.start();
c3.start();
c4.start();
}
}