산업 제조
산업용 사물 인터넷 | 산업자재 | 장비 유지 보수 및 수리 | 산업 프로그래밍 |
home  MfgRobots >> 산업 제조 >  >> Industrial programming >> java

자바 블로킹큐

자바 차단 대기열

이 자습서에서는 Java BlockingQueue 인터페이스와 해당 메서드에 대해 알아봅니다.

BlockingQueue 자바 Collections의 인터페이스 프레임워크는 Queue을 확장합니다. 상호 작용. 모든 작업이 성공적으로 수행될 수 있을 때까지 대기할 수 있습니다.

예를 들어, 빈 대기열에서 요소를 삭제하려는 경우 차단 대기열을 사용하면 대기열에 삭제할 일부 요소가 포함될 때까지 삭제 작업이 대기할 수 있습니다.

<시간>

BlockingQueue를 구현하는 클래스

BlockingQueue 이후 인터페이스이므로 직접 구현할 수 없습니다.

BlockingQueue의 기능을 사용하려면 , 이를 구현하는 클래스를 사용해야 합니다.

<시간>

차단 대기열을 사용하는 방법

java.util.concurrent.BlockingQueue을 가져와야 합니다. BlockingQueue를 사용하기 위한 패키지 .

// Array implementation of BlockingQueue
BlockingQueue<String> animal1 = new ArraryBlockingQueue<>();

// LinkedList implementation of BlockingQueue
BlockingQueue<String> animal2 = new LinkedBlockingQueue<>();

여기에서 animal1 개체를 만들었습니다. 및 animal2 ArrayBlockingQueue 클래스 및 LinkedBlockingQueue , 각각. 이러한 개체는 BlockingQueue의 기능을 사용할 수 있습니다. 인터페이스.

<시간>

BlockingQueue의 방법

큐가 가득 찼는지 비어 있는지에 따라 큐를 차단하는 방법은 3가지 범주로 나눌 수 있습니다.

예외를 발생시키는 메소드

<시간>

값을 반환하는 메서드

offer() 및 poll()에 대한 추가 정보

offer()poll() 메서드는 시간 초과와 함께 사용할 수 있습니다. 즉, 시간 단위를 매개변수로 전달할 수 있습니다. 예를 들어,

offer(value, 100, milliseconds)

여기,

이것은 offer()를 의미합니다. 메소드는 100에 대한 블로킹 큐에 요소를 삽입하려고 시도합니다. 밀리초. 100밀리초 안에 요소를 삽입할 수 없는 경우 메서드는 false를 반환합니다. .

참고: milliseconds 대신 , 다음과 같은 시간 단위도 사용할 수 있습니다. days , hours , minutes , seconds , microsecondsnanoseconds offer()poll() 방법.

<시간>

작업을 차단하는 방법

BlockingQueue 또한 작업을 차단하고 대기열이 가득 차거나 비어 있는 경우 대기하는 방법을 제공합니다.

요소를 대기열에 삽입하려고 한다고 가정해 보겠습니다. 대기열이 가득 차면 put() 메서드는 큐에 요소를 삽입할 공간이 있을 때까지 기다립니다.

마찬가지로 대기열에서 요소를 삭제하려는 경우입니다. 대기열이 비어 있으면 take() 이 메서드는 삭제할 요소가 대기열에 포함될 때까지 기다립니다.

<시간>

ArrayBlockingQueue에서 BlockingQueue 구현

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

class Main {

    public static void main(String[] args) {
      // Create a blocking queue using the ArrayBlockingQueue
      BlockingQueue<Integer> numbers = new ArrayBlockingQueue<>(5);

      try {
        // Insert element to blocking queue
        numbers.put(2);
        numbers.put(1);
        numbers.put(3);
        System.out.println("BLockingQueue: " + numbers);

        // Remove Elements from blocking queue
        int removedNumber = numbers.take();
        System.out.println("Removed Number: " + removedNumber);
      }

      catch(Exception e) {
          e.getStackTrace();
      }
    }
}

출력

BlockingQueue: [2, 1, 3]
Removed Element: 2

ArrayBlockingQueue에 대해 자세히 알아보려면 , Java ArrayBlockingQueue를 방문하십시오.

<시간>

BlockingQueue가 필요한 이유

자바에서는 BlockingQueue 스레드 안전으로 간주됩니다. 수집. 멀티스레딩 작업에 도움이 될 수 있기 때문입니다.

한 스레드가 큐에 요소를 삽입하고 다른 스레드가 큐에서 요소를 제거한다고 가정합니다.

이제 첫 번째 스레드가 느리게 실행되면 블로킹 큐는 첫 번째 스레드가 작업을 완료할 때까지 두 번째 스레드를 기다리게 할 수 있습니다.


java

  1. 자바 연산자
  2. 자바 주석
  3. 자바 for-each 루프
  4. 자바 문자열
  5. 자바 인터페이스
  6. 자바 익명 클래스
  7. 자바 리소스 사용
  8. 자바 주석
  9. 자바 어설션
  10. 자바 벡터