91名师指路-头部
91名师指路

阻塞队列 SynchronousQueue的使用(三)

由于某些原因,现在不支持支付宝支付,如需要购买源码请加博主微信进行购买,微信号:13248254750

SynchronousQueue:同步队列即生产一个消费一个,实现零库存的概念。即如果生产了1个,如果不消费掉,另外生产的那个将一直阻塞在那里。


代码如下:

package com.mszl.thread;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.SynchronousQueue;

/**
* 功能:SynchronousQueue演示
* 备注:更多资料请访问 http://www.91mszl.com
* @author bobo teacher
*/
public class SynchronousQueueDemo {

public static void main(String[] args) {
BlockingQueue<String> bq=new SynchronousQueue<>();

// 线程1进行生产
Thread t1=new Thread(new Runnable() {
@Override
public void run() {
try {
System.out.println(Thread.currentThread().getName() + "\t" + "生产了A");
bq.put("A");

System.out.println(Thread.currentThread().getName() + "\t" + "生产了B");
bq.put("B");

System.out.println(Thread.currentThread().getName() + "\t" + "生产了C");
bq.put("C");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
t1.start();

// 线程2进行消费
Thread t2=new Thread(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(3000);
System.out.println(Thread.currentThread().getName() + "\t" + "消费了A");
bq.take();

Thread.sleep(3000);
System.out.println(Thread.currentThread().getName() + "\t" + "消费了B");
bq.take();

Thread.sleep(3000);
System.out.println(Thread.currentThread().getName() + "\t" + "消费了C");
bq.take();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
t2.start();
}


}


执行结果:

Thread-0	生产了A
Thread-1 消费了A
Thread-0 生产了B
Thread-1 消费了B
Thread-0 生产了C
Thread-1 消费了C


2019-12-02 10:39:20     阅读(1054)

名师出品,必属精品    https://www.91mszl.com

联系博主    
用户登录遮罩层
x

账号登录

91名师指路-底部