生产者
package com.ProductCusromer.method3;
import java.util.concurrent.BlockingQueue;
/**
* @author Millet
* @date 2020/3/30 21:28
*/
public class Product4 implements Runnable {
private BlockingQueue queue;
private String name;
public Product4(String name, BlockingQueue queue) {
this.queue = queue;
this.name = name;
}
@Override
public void run() {
while(true){
try {
int val = (int) Math.random();
queue.put(val);
System.out.println(name + "生产:"+val+".当前队列长度:"+ queue.size());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
消费者
package com.ProductCusromer.method3;
import java.util.concurrent.BlockingDeque;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
/**
* @author Millet
* @date 2020/3/30 21:28
*/
public class Consumer4 implements Runnable{
private BlockingQueue queue;
private String name;
public Consumer4(String name, BlockingQueue queue) {
this.queue = queue;
this.name = name;
}
@Override
public void run() {
try {
while (true){
int val = (int) queue.take();
System.out.println(name + "消费:"+val+".当前队列长度:"+ queue.size());
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
package com.ProductCusromer.method3;
import com.ProductCusromer.method1.Consumer1;
import com.ProductCusromer.method1.Product1;
import javax.persistence.criteria.CriteriaBuilder;
import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/**
* @author Millet
* @date 2020/3/30 20:33
*/
public class Main {
public static void main(String[] args) {
BlockingQueue<Integer> queue = new LinkedBlockingQueue<>(20);
Product4 producer1 = new Product4("生产1号", queue);
Product4 producer2 = new Product4("生产2号", queue);
Product4 producer3 = new Product4("生产3号", queue);
Consumer4 consumer1 = new Consumer4("消费1号", queue);
Consumer4 consumer2 = new Consumer4("消费2号", queue);
// 开始producer线程进行生产
new Thread(producer1).start();
new Thread(producer2).start();
new Thread(producer3).start();
// 开始consumer线程进行消费。
new Thread(consumer1).start();
new Thread(consumer2).start();
}
}