How to implement a queue using the SynchronousQueue class in Java?

In Java, a SynchronousQueue is a special type of blocking queue that can only have one element at a time. When a thread tries to put an element into the queue, it will be blocked until another thread tries to take that element out of the queue.

To achieve the functionality of queuing, you can utilize the offer() and take() methods of SynchronousQueue.

Here is a simple example code:

import java.util.concurrent.SynchronousQueue;

public class QueueExample {
    private static SynchronousQueue<String> queue = new SynchronousQueue<>();

    public static void main(String[] args) {
        // 创建多个线程
        for (int i = 0; i < 5; i++) {
            Thread thread = new Thread(() -> {
                try {
                    String name = Thread.currentThread().getName();
                    System.out.println(name + " 正在排队...");
                    queue.offer(name); // 将线程名称放入队列
                    System.out.println(name + " 排队成功,开始工作");
                    Thread.sleep(1000);
                    System.out.println(name + " 工作完成,离开队列");
                    queue.take(); // 从队列中取出线程名称
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            });
            thread.start();
        }
    }
}

In this example, five threads are created, each attempting to put their own name into a queue and then waiting for other threads to take out their name. While one thread is blocked, the other threads will continue to execute until the blocked thread is awakened.

Please note that the SynchronousQueue does not store elements but serves as an intermediary for inter-thread communication. Therefore, in the process of using it, ensure that there are other threads to retrieve elements from the queue; otherwise, it may cause threads to block indefinitely.

bannerAds