4.3 KiB
4.3 KiB
直接看码
import java.util.Queue;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;
/**
* @author dss
* @projectName queueDemo
* @date 2021/12/1
* @description:
*/
public class QueueDemo01 {
public static void main(String[] args) {
//队列模拟库存 容量为10
Queue<ManTou> manTouQueue = new ArrayBlockingQueue<ManTou>(10);
//放入容量对象
Container container = new Container(manTouQueue);
//生产者线程自增
final AtomicInteger pCount = new AtomicInteger(1);
//消费者线程自增
final AtomicInteger cCount = new AtomicInteger(1);
//设置生产者线程名称
ThreadFactory producer = new ThreadFactory() {
public Thread newThread(Runnable r) {
return new Thread(r,"生产"+pCount.getAndIncrement()+"线");
}
};
//设置消费者线程名称
ThreadFactory consumer = new ThreadFactory() {
public Thread newThread(Runnable r) {
return new Thread(r,"北京"+cCount.getAndIncrement()+"店");
}
};
//生产者线程池
ExecutorService producers = Executors.newCachedThreadPool(producer);
//消费者线程池
ExecutorService consumers = Executors.newCachedThreadPool(consumer);
for (int i = 0; i < 5; i++) {
consumers.execute(new Consumer(container));
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
producers.execute(new Producer(container));
}
}
}
//容器
class Container{
//馒头自增编号
private int no;
//馒头队列
private Queue<ManTou> manTouQueue;
Container(Queue<ManTou> manTouQueue){
this.manTouQueue=manTouQueue;
}
public int getNo() {
return no;
}
public void setNo(int no) {
this.no = no;
}
public Queue<ManTou> getQueue() {
return manTouQueue;
}
}
//产品
class ManTou{
//编号
private int no;
ManTou(int no){
this.no = no;
};
public int getNo() {
return no;
}
}
//生产
class Producer implements Runnable{
//容器
private Container container;
Producer(Container container){
this.container=container;
}
public void run() {
//循环生产
while (true){
//对容器进行同步 保证线程安全
synchronized (container){
//将生产馒头添加到队列
boolean flag = container.getQueue().offer(new ManTou(container.getNo()+1));
if (flag){
//编号加一
container.setNo(container.getNo()+1);
//记录生产的馒头
System.out.println(Thread.currentThread().getName()+"生产馒头"+container.getNo());
}else{
//提示队列已满请先消费
System.out.println("库存满了快去销售~");
}
}
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
//消费
class Consumer implements Runnable{
//容器
private Container container;
Consumer(Container container){
this.container=container;
}
public void run() {
//循环销售
while (true){
synchronized (container){
//获取馒头
ManTou manTou = container.getQueue().poll();
if (manTou!=null){
//记录销售馒头
System.out.println(Thread.currentThread().getName()+"出售馒头"+manTou.getNo());
}else{
System.err.println("卖完了快去生产~");
}
System.err.println("当前库存"+container.getQueue().size());
}
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}