How to use synchronousqueue in Java?

In Java, you can use SynchronousQueue for synchronized communication between threads. It is a blocking queue that does not store elements, and the main feature is that the producer thread must wait for the consumer thread to consume an element before producing a new one.

Here is an example code using SynchronousQueue:

import java.util.concurrent.SynchronousQueue;

public class SynchronousQueueExample {
    public static void main(String[] args) {
        SynchronousQueue<Integer> queue = new SynchronousQueue<>();

        // 创建生产者线程
        Thread producer = new Thread(() -> {
            try {
                int value = 1;
                while (true) {
                    // 将元素放入队列
                    queue.put(value);
                    System.out.println("生产者生产了:" + value);
                    value++;
                    // 模拟生产者生产时间
                    Thread.sleep(1000);
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });

        // 创建消费者线程
        Thread consumer = new Thread(() -> {
            try {
                while (true) {
                    // 从队列中取出元素
                    int value = queue.take();
                    System.out.println("消费者消费了:" + value);
                    // 模拟消费者消费时间
                    Thread.sleep(2000);
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });

        // 启动生产者和消费者线程
        producer.start();
        consumer.start();
    }
}

In the above code, first a SynchronousQueue instance is created. Then a producer thread is created to continuously produce elements and put them into the queue. A consumer thread is created to continuously take elements from the queue and consume them. The producer and consumer threads run simultaneously, but the producer must wait for the consumer to finish consuming an element before it can produce new elements, thus achieving synchronization between the threads.

bannerAds