import com.google.gson.JsonObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.concurrent.LinkedBlockingDeque;
public class CjThreadMQ {
private static final LinkedBlockingDeque<JsonObject> mq = new LinkedBlockingDeque<>();
private static final Logger logger = LoggerFactory.getLogger(CjThreadMQ.class);
// 消息发布者线程
static Thread producerThread = new Thread(new Runnable() {
@Override
public void run() {
try {
int i = 1;
while (true) {
Thread.sleep(1000);
JsonObject msg = new JsonObject();
msg.addProperty("uid", i++);
boolean isOk = mq.offer(msg);
System.out.println(Thread.currentThread().getName() + "-->入队" + (isOk ? "成功" : "失败") + ",内容:" + msg);
}
} catch (Exception e) {
logger.error("入队异常信息", e);
}
}
}, "消息发布者");
// 消息消费者线程
static Thread consumerThread = new Thread(new Runnable() {
@Override
public void run() {
try {
while (true) {
JsonObject msg = mq.poll();
if (msg != null) {
System.out.println(Thread.currentThread().getName() + "-->消费内容:" + msg);
}
}
} catch (Exception e) {
logger.error("消费异常信息", e);
}
}
}, "消息消费者");
public static void main(String[] args) {
producerThread.start();
consumerThread.start();
}
}
停止运行,显示