原 阻塞队列 SynchronousQueue的使用(三)
版权声明:本文为博主原创文章,请尊重他人的劳动成果,转载请附上原文出处链接和本声明。
本文链接:https://www.91mszl.com/zhangwuji/article/details/1143
代码如下:
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 阅读(1162)
名师出品,必属精品 https://www.91mszl.com
博主信息