packagecom.hdwang;importcom.alibaba.fastjson.JSON;importjava.util.concurrent.BlockingQueue;importjava.util.concurrent.LinkedBlockingQueue;/*** Created by hdwang on 2018/4/17.*/
public classMultiQueueSynTest {static BlockingQueue queue1 = newLinkedBlockingQueue();static BlockingQueue queue2 = newLinkedBlockingQueue();static int seq = 1;/*** 同步锁*/
static Object lock = newObject();static voidcommit(String msg){synchronized(lock) {
Packet packet= newPacket();
packet.setSeq(seq++);
packet.setMsg(msg);try{//queue1.put(packet);//阻塞式添加元素
while(queue1.size()== Integer.MAX_VALUE){ //队满,等待
lock.wait();
}
queue1.offer(packet);//非阻塞式添加元素即可
System.out.println("commit msg:" +JSON.toJSONString(packet));
lock.notifyAll();//通知等待线程
}catch(InterruptedException e) {
e.printStackTrace();
}
}
}static voidsend(){while(true) {synchronized(lock) {try{//Packet packet = queue1.take();//阻塞式取元素//queue2.put(packet);
while(queue1.isEmpty()) { //队空,等待
lock.wait(); //等待,交出锁
}
Packet packet= queue1.poll(); //非阻塞式取元素即可
System.out.println("send msg:" +JSON.toJSONString(packet));
lock.notifyAll();//通知等待线程
while (queue2.size() == Integer.MAX_VALUE){ //队满,等待
lock.wait(); //等待,交出锁
}
queue2.offer(packet);
System.out.println("msg->queue2:"+JSON.toJSONString(packet));
lock.notifyAll();//通知等待线程
}catch(InterruptedException e) {
e.printStackTrace();
}
}
}
}public static voidmain(String[] args) {//生产者1
new Thread(newRunnable() {
@Overridepublic voidrun() {while(true){ //不断产生消息
commit("hello1");try{
Thread.sleep(3000);
}catch(InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();//生产者2
new Thread(newRunnable() {
@Overridepublic voidrun() {while(true){ //不断产生消息
commit("hello2");try{
Thread.sleep(3000);
}catch(InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();//消费者
new Thread(newRunnable() {
@Overridepublic voidrun() {
send();
}
}).start();
}static classPacket{intseq;
String msg;public intgetSeq() {returnseq;
}public void setSeq(intseq) {this.seq =seq;
}publicString getMsg() {returnmsg;
}public voidsetMsg(String msg) {this.msg =msg;
}
}
}