>  기사  >  Java  >  Java의 차단 대기열 BlockingQueue에 대한 샘플 코드 분석

Java의 차단 대기열 BlockingQueue에 대한 샘플 코드 분석

黄舟
黄舟원래의
2017-04-01 10:30:071521검색

이 글에서는 주로 java의 queueBlockingQueue 차단에 대한 자세한 설명과 예시를 소개하고 있습니다. 필요하신 분들은

블로킹큐 차단에 대한 자세한 설명과 예시를 참고하세요. java.

BlockingQueue는 멀티 스레드의 데이터 전송에 적합한 솔루션입니다. 우선 BlockingQueue는 대략 4개의 구현 클래스를 가지고 있습니다. 매우 특별한 대기열입니다. BlockQueue가 비어 있으면 BlockingQueue에서 항목을 검색하는 작업이 차단되고 대기 상태로 들어가며, BlockingQueue가 무언가에 들어갈 때까지 깨어나지 않습니다. BlockingQueue가 꽉 찼습니다. 이를 저장하려고 하면 작업도 차단되고 BlockingQueue에 공간이 생길 때까지 작업을 계속하기 위해 깨어나지 않습니다.

BlockingQueue의 네 가지 구현 클래스:

1.

Array

BlockingQueue: 지정된 크기의 BlockingQueue, 해당 생성자 int 매개변수는 크기를 나타내기 위해 사용되어야 합니다. 개체는 FIFO(선입선출) 순서로 정렬됩니다. 2. 생성자가 지정된 크기의 매개변수를 사용하는 경우 생성된 BlockingQueue에는 크기 제한이 있습니다. 크기 매개변수를 사용하지 않는 경우 생성된 BlockingQueue의 크기는 Integer.MAX_VALUE에 따라 결정됩니다. 선입선출) )순차 정렬

3. PriorityBlockingQueue: LinkedBlockQueue와 유사하지만 포함된 객체의 정렬은 FIFO가 아니라 객체의 자연스러운 정렬 순서를 기반으로 합니다. 생성자의 비교기에 의해 결정되는 순서.

4.SynchronousQueue: 특수 BlockingQueue, 해당 작업은 넣기와 가져오기를 통해 교대로 완료되어야 합니다.

일반적인 방법 of BlockingQueue:

1) add(anObject

): BlockingQueue에 anObject를 추가합니다. 즉, BlockingQueue가 이를 수용할 수 있으면 true를 반환하고 그렇지 않으면 예외가 발생합니다. 보고됨

2) Offer(anObject ): 가능하면 BlockingQueue에 anObject를 추가함을 나타냅니다. 즉, BlockingQueue가 이를 수용할 수 있으면 true를 반환하고, 그렇지 않으면 false를 반환합니다.

3)put(anObject): BlockingQueue에 anObject를 추가합니다. BlockQueue에 공간이 없으면 계속하기 전에 BlockingQueue에 공간이 있을 때까지 이 메서드를 호출하는 스레드가 차단됩니다. 즉시 꺼낼 수 없으면 time 매개변수에 지정된 시간 동안 기다릴 수 있습니다. 꺼낼 수 없으면
null


을 반환합니다. 5) take(): BlockingQueue를 제거합니다. 첫 번째 개체는 BlockingQueue가 비어 있으면 차단되고 새 개체가 Blocking

에 추가될 때까지 대기 상태로 들어갑니다. 예:
이 예는 주로 시뮬레이션 생산자와 소비자 사이의 워크플로는 소비자가 소비자가 소비할 제품을 생산자가 생산할 때까지 소비자가 기다리는 간단한 시나리오입니다.

생산자:

package com.gefufeng;

import java.util.concurrent.BlockingQueue;

public class Producter implements Runnable{
 private BlockingQueue<String> blockingQueue;
 
 public Producter(BlockingQueue<String> blockingQueue){
 this.blockingQueue = blockingQueue;
 }

 @Override
 public void run() {
 try {
  blockingQueue.put("我生产的" + Thread.currentThread().getName());
  System.out.println("我生产的" + Thread.currentThread().getName());
 } catch (InterruptedException e) {
  // TODO Auto-generated catch block
  e.printStackTrace();
  System.out.println("生产失败");
 }
 
 }
 
 

}

소비자:

package com.gefufeng;

import java.util.concurrent.BlockingQueue;

public class Customer implements Runnable{
 private BlockingQueue<String> blockingQueue;
 
 public Customer(BlockingQueue<String> blockingQueue){
 this.blockingQueue = blockingQueue;
 }

 @Override
 public void run() {
 for(;;){
  try {
  String threadName = blockingQueue.take();
  System.out.println("取出:" + threadName);
  } catch (InterruptedException e) {
  // TODO Auto-generated catch block
  e.printStackTrace();
  System.out.println("取出失败");
  }
 }
 }

}

실행 클래스:

package com.gefufeng;

import java.util.concurrent.ArrayBlockingQueue;

public class Executer {
 
 public static void main(String[] args) {
 ArrayBlockingQueue<String> arrayBlockingQueue = new ArrayBlockingQueue<String>(2);
 Producter producter = new Producter(arrayBlockingQueue);
 Customer cusotmer = new Customer(arrayBlockingQueue);
 new Thread(cusotmer).start();
 for(;;){
  try {
  Thread.sleep(2000);
  new Thread(producter).start();
  } catch (InterruptedException e) {
  // TODO Auto-generated catch block
  e.printStackTrace();
  }
 }
 
 
 
 }

}

첫 번째는 소비자

루프

제품을 기다리는 중 루프에서 처음으로 BlockingQueue.take()를 실행하면 제품을 얻을 수 없어 차단 상태로 진입하고 2초 후에 생산자가 제품을 생산하므로 BlockingQueue가 해당 제품을 가져옵니다. 소비자는 로그를 읽은 후 두 번째 루프를 실행하고 BlockingQueue.take()가 제품을 다시 가져오지 못하여 다시 차단 상태에 들어간 것을 발견했습니다. . . 순환

위 내용은 Java의 차단 대기열 BlockingQueue에 대한 샘플 코드 분석의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.