同步调用 java_java同步代码(synchronized)中使用BlockingQueue

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;

}

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值