JUC之SynchronousQueue同步队列

结构图

在这里插入图片描述

SynchronousQueue 简介

  • 大小只有1个;
  • 属于同步队列;
  • 必须等待添加的元素取出才会继续添加,否则一直等待。

SynchronousQueue 测试案例

验证上面所描述的特性,下面编写代码观察结果:

1、持续添加3个数据信息至 SynchronousQueue 中。
2、读取操作采取延迟读取的方式。
3、观察日志信息。

package demo5_4;

import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.TimeUnit;

/**
 * 同步队列;
 * 大小只有1;
 * 必须等待存放的数据消费掉后,才会继续向队列中增加数据,否则一直等待!
 */
public class SynchronousQueueDemo {
    
    
    public static void main(String[] args) {
    
    
        SynchronousQueue synchronousQueue = new SynchronousQueue();
        // 存数据
        new Thread(()->{
    
    
            try {
    
    
                System.out.println(Thread.currentThread().getName() + "put 1 "+System.currentTimeMillis());
                synchronousQueue.put("1");
                System.out.println(Thread.currentThread().getName() + "put 2 "+System.currentTimeMillis());
                synchronousQueue.put("2");
                System.out.println(Thread.currentThread().getName() + "put 3 "+System.currentTimeMillis());
                synchronousQueue.put("3");

            } catch (InterruptedException e) {
    
    
                e.printStackTrace();
            }
        },"A").start();

        // 获取数据
        new Thread(()->{
    
    
            try {
    
    
                TimeUnit.SECONDS.sleep(3);
                System.out.println(Thread.currentThread().getName()+" 获取 "+synchronousQueue.take()+" 成功 "+System.currentTimeMillis());
                TimeUnit.SECONDS.sleep(3);
                System.out.println(Thread.currentThread().getName()+" 获取 "+synchronousQueue.take()+" 成功 "+System.currentTimeMillis());
                TimeUnit.SECONDS.sleep(3);
                System.out.println(Thread.currentThread().getName()+" 获取 "+synchronousQueue.take()+" 成功 "+System.currentTimeMillis());
            } catch (InterruptedException e) {
    
    
                e.printStackTrace();
            }
        },"B").start();
    }
}

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_38322527/article/details/115079824
今日推荐