>  기사  >  Java  >  Java의 차단 대기열 BlockingQueue 예제에 대한 자세한 설명

Java의 차단 대기열 BlockingQueue 예제에 대한 자세한 설명

Y2J
Y2J원래의
2017-04-27 09:37:421688검색

이 글에서는 주로 Java의 BlockingQueue 차단에 대한 자세한 설명과 예시를 소개합니다. 필요한 친구는

Java의 차단 큐 BlockingQueue에 대한 자세한 설명과 예시

BlockingQueue는 다중 스레드의 데이터 전송에 대한 좋은 솔루션입니다. 우선 BlockingQueue는 대략 4개의 구현 클래스를 가지고 있습니다. 이는 BlockQueue가 비어 있는 경우 작업이 수행되는 방식입니다. BlockingQueue에서 항목을 가져오는 작업은 차단되고 대기 상태로 들어가며 BlockingQueue에 항목이 포함될 때까지 깨어나지 않습니다. 마찬가지로 BlockingQueue가 가득 차면 여기에 항목을 저장하려는 모든 작업도 차단됩니다. 대기 상태로 들어가며 BlockingQueue에 공간이 생길 때까지 깨어나지 않고 작업을 계속합니다.

BlockingQueue의 네 가지 구현 클래스:

1.ArrayBlockingQueue: 지정된 크기의 BlockingQueue 생성자는 크기를 나타내기 위해 int 매개변수를 사용해야 합니다. FIFO(선입선출) 순서로 정렬됩니다.


2. LinkedBlockingQueue: 가변 크기의 BlockingQueue 생성자가 지정된 크기의 매개변수를 사용하는 경우 생성된 BlockingQueue에는 크기 제한이 있습니다. 크기 매개변수가 없는 경우 생성된 BlockingQueue의 크기는 Integer.MAX_VALUE에 의해 결정됩니다. 여기에 포함된 객체는 FIFO(선입 선출) 순서로 정렬됩니다.


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


4.SynchronousQueue: 특별한 BlockingQueue는 넣기와 가져오기를 번갈아가며 완료해야 합니다.

BlockingQueue의 일반적인 방법:

1) add(anObject): anObject를 추가합니다. BlockingQueue, 즉 BlockingQueue를 수용할 수 있으면 true를 반환하고 그렇지 않으면 예외가 보고됩니다.


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


3)put(anObject): BlockingQueue에 공간이 없으면 이를 호출하는 스레드입니다. 계속하기 전에 BlockingQueue에 공간이 생길 때까지 메서드가 차단됩니다.


4)poll(time): BlockingQueue에서 첫 번째 개체를 즉시 꺼낼 수 없으면 기다릴 수 있습니다. time 매개변수로 지정된 시간 동안 꺼낼 수 없는 경우 null을 반환합니다.


5)take(): 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();
  }
 }
 }
}

먼저, 소비자는 루프에서 다음을 기다립니다. product, 루프에서 처음으로 BlockingQueue.take()가 실행되면 제품을 생산할 수 없으므로 차단 상태로 들어가고 2초 후에 생산자가 제품을 생산하므로 BlockingQueue가 제품을 가져오고 인쇄합니다. 두 번째 루프를 실행한 후, BlockingQueue.take()가 다시 제품을 가져오지 못한 것으로 확인되어 다시 차단 상태에 들어갔습니다. . . 순환

위 내용은 Java의 차단 대기열 BlockingQueue 예제에 대한 자세한 설명의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

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