Java如何使用ArrayBlockingQueue?

ArrayBlockingQueue是的一种实现,该实现java.util.concurrent.BlockingQueue将队列元素内部存储在数组中。在ArrayBlockingQueue当对象被初始化时,由该构造能够存储元件,用于尺寸限定。定义大小后,将无法更改或调整大小。

下面的代码段演示了ArrayBlockingQueue该类。我们初始化队列,以允许其内部数组最多存储64个元素。

package org.nhooo.example.util.concurrent;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

public class ArrayBlockingQueueExample {
    private BlockingQueue<String> sharedQueue = new ArrayBlockingQueue<>(64);

    public static void main(String[] args) {
        new ArrayBlockingQueueExample().createProducerConsumer();
    }

    private void createProducerConsumer() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    System.out.println(Thread.currentThread().getName());
                    try {
                        sharedQueue.put("DATA");
                        Thread.sleep(500);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }, "Producer Thread").start();

        new Thread(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    System.out.print(Thread.currentThread().getName() + "=> ");
                    try {
                        System.out.println(sharedQueue.take());
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }, "Consumer Thread-1").start();
    }
}