一、基于阻塞队列实现生产者和消费者循环生产消费。
1、解题思路基于自定义线程+ArrayBlockQuery实现
1.1 生产者
package com.boot.skywalk.util.queue;
import java.util.concurrent.BlockingQueue;
public class Producer implements Runnable{
private BlockingQueue<Menu> blockingQueue;
public Producer(BlockingQueue blockingQueue){
this.blockingQueue=blockingQueue;
}
@Override
public void run() {
for(int i=1;i<=100;i++){
Menu menu = new Menu(i + "code");
try {
Thread.sleep(100);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
try {
blockingQueue.put(menu);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
System.out.println("生产商品:"+menu.getMessage());
}
// 作为退出标记
Menu exit = new Menu("exit");
try {
blockingQueue.put(exit);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
1.2 消费者
package com.boot.skywalk.util.queue;
import java.util.concurrent.BlockingQueue;
public class Consumer implements Runnable{
private BlockingQueue<Menu> blockingQueue;
public Consumer(BlockingQueue blockingQueue){
this.blockingQueue=blockingQueue;
}
@Override
public void run() {
Menu menu;
try {
while(!(menu=blockingQueue.take()).getMessage().equals("exit")){
Thread.sleep(100);
System.out.println("消费商品:"+menu.getMessage());
}
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
1.3 测试代码
package com.boot.skywalk.util.queue;
public class Menu {
private String message;
public Menu(String message) {
this.message = message;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
package com.boot.skywalk.util.queue;
import java.util.concurrent.ArrayBlockingQueue;
public class Client {
public static void main(String[] args) throws InterruptedException {
ArrayBlockingQueue<Object> blockingQueue = new ArrayBlockingQueue<>(10);
Producer producer = new Producer(blockingQueue);
Consumer consumer = new Consumer(blockingQueue);
System.out.println("消费开始");
Thread produceThread = new Thread(producer);
Thread consumerThread = new Thread(consumer);
produceThread.start();
consumerThread.start();
produceThread.join();
consumerThread.join();
System.out.println("消费结束");
}
}
运行结果


二、多个线程顺序执行
1、解题思路基于CountDownLatch的countDown和await实现.
package co

最低0.47元/天 解锁文章
962

被折叠的 条评论
为什么被折叠?



