Java 스레드 대기열 사용 - LinkedBlockingQueue

LinkedBlockingQueue는 데이터 노드의 연결된 목록을 내부에 유지하는 연결 목록 기반의 차단 대기열입니다. 용량을 지정하거나 지정하지 않을 수 있습니다. 지정되지 않은 경우 기본 용량은 무제한 대기열인 Integer.MAX_VALUE입니다. 생산자와 소비자의 동기화를 유지하기 위해 별도의 잠금(ReentrantLock)을 사용합니다.

LinkedBlockingQueue는 무제한 버퍼를 구현하는 데 사용할 수 있습니다.예를 들어 다음 코드는 기본 용량으로 LinkedBlockingQueue를 생성하고 여기에 10개의 요소를 추가합니다. 보다시피 대기열에 용량 제한이 없기 때문에 삽입 작업이 차단되지 않습니다.

import java.util.concurrent.LinkedBlockingQueue;

public class LinkedBlockingQueueDemo {
    public static void main(String[] args) {
        // 创建一个默认容量的链表阻塞队列
        LinkedBlockingQueue<Integer> lbq = new LinkedBlockingQueue<>();
        // 向队列中添加10个元素
        for (int i = 0; i < 10; i++) {
            try {
                System.out.println("Trying to put " + i + " into queue");
                lbq.put(i);
                System.out.println("Successfully put " + i + " into queue");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

출력 결과(일부):

Trying to put 0 into queue
Successfully put 0 into queue
Trying to put 1 into queue
Successfully put 1 into queue
Trying to put 2 into queue
Successfully put 2 into queue
Trying to put 3 into queue
Successfully put 3 into queue
Trying to put 4 into queue
Successfully put 4 into queue
Trying to put 5 into queue
Successfully put 5 into queue
// 此时队列没有满,插入操作不会被阻塞,直到达到Integer.MAX_VALUE的上限

Supongo que te gusta

Origin blog.csdn.net/caicai250/article/details/131441550
Recomendado
Clasificación