SynchronousQueue of JUC

Structure chart

Insert picture description here

Introduction to SynchronousQueue

  • The size is only 1;
  • Belongs to a synchronous queue;
  • You must wait for the added element to be taken out before continuing to add it, otherwise it has been waiting.

SynchronousQueue test case

To verify the characteristics described above, write the following code to observe the results:

1. Continue to add 3 data messages to the SynchronousQueue.
2. The read operation adopts a delayed read method.
3. Observe the log information.

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();
    }
}

Insert picture description here

Guess you like

Origin blog.csdn.net/qq_38322527/article/details/115079824