logo

자바 대기열

큐는 다른 데이터 구조와 마찬가지로 특정 방식으로 요소를 저장하는 데 사용되는 또 다른 종류의 선형 데이터 구조입니다. 간단히 말해서 대기열은 동일한 종류의 요소를 저장하는 Java 프로그래밍 언어의 데이터 구조 유형이라고 말할 수 있습니다. 대기열의 구성 요소는 FIFO(선입 선출) 동작으로 저장됩니다. 대기열 컬렉션에는 두 개의 끝(즉, 앞과 뒤)이 있습니다. 대기열에는 앞과 뒤의 두 끝이 있습니다.

다음 그림은 Java 대기열의 FIFO(선입선출) 속성을 완벽하게 설명합니다.

자바 큐

이전 이미지에서 설명했듯이 큐는 두 개의 터미널, 즉 시작(앞)과 끝(뒤)이 있는 선형 데이터 구조임을 알 수 있습니다. 구성 요소는 대기열의 뒤쪽 끝에서 대기열 내부에 추가되고 구성 요소는 대기열의 앞쪽 끝에서 추출됩니다.

대기열은 다음의 인터페이스입니다. 자바 이는 Java.util 패키지에 속합니다. 또한 Collection 인터페이스를 확장합니다.

Java 대기열 인터페이스의 일반적인 표현은 다음과 같습니다.

 public interface Queue extends Collection 

위에서 대기열이 인터페이스라고 논의한 것처럼 인터페이스를 인스턴스화할 수 없기 때문에 대기열도 인스턴스화할 수 없다고 말할 수도 있습니다. 사용자가 Java에서 Queue 인터페이스의 기능을 구현하려는 경우 Queue 인터페이스를 구현하는 일부 견고한 클래스가 있어야 합니다.

지도 자바

Java 프로그래밍 언어에는 대기열 인터페이스를 구현하는 데 사용되는 두 가지 클래스가 있습니다. 이러한 수업은 다음과 같습니다.

자바 대기열

Java 대기열의 특성

Java Queue는 프로그래밍 세계에서 가장 중요한 데이터 구조 중 하나로 간주될 수 있습니다. Java Queue는 그 속성 때문에 매력적입니다. Java 큐 데이터 구조의 중요한 속성은 다음과 같습니다.

  • Java Queue는 FIFO(선입선출) 방식을 따릅니다. 이는 요소가 큐의 마지막 부분에 입력되고 맨 앞에서 제거됨을 나타냅니다.
  • Java Queue 인터페이스는 포함, 삭제 등과 같은 Collection 인터페이스의 모든 규칙과 프로세스를 제공합니다.
  • Queue 인터페이스를 구현하는 데 사용되는 두 가지 클래스가 있습니다. 이러한 클래스는 LinkedList 및 PriorityQueue입니다.
  • 이 두 가지 외에 Queue 인터페이스를 구현하는 데 사용되는 Array Blocking Queue 클래스가 있습니다.
  • 큐에는 제한되지 않은 큐와 제한된 큐의 두 가지 유형이 있습니다. java.util 패키지의 일부인 큐는 Unbounded 큐라고 하며 제한된 큐는 java.util.concurrent 패키지에 있는 큐입니다.
  • Deque 또는 (이중 종료 대기열)은 양쪽 끝에서 요소를 포함하고 삭제하는 대기열 유형이기도 합니다.
  • deque는 스레드로부터 안전한 것으로 간주됩니다.
  • 차단 대기열은 스레드로부터 안전한 대기열 유형 중 하나이기도 합니다. 차단 대기열은 생산자-소비자 쿼리를 구현하는 데 사용됩니다.
  • 차단 대기열은 null 요소를 지원하지 않습니다. 차단 대기열에서 null 값과 유사한 작업이 시도되면 NullPointerException도 발생합니다.

대기열 구현

Queue 구현에 사용되는 클래스

큐의 기능을 구현하는 데 사용되는 클래스는 다음과 같습니다.

Queue 구현에 사용되는 인터페이스

Java 인터페이스는 Java 대기열 구현에도 사용됩니다. 대기열의 기능을 구현하는 데 사용되는 인터페이스는 다음과 같습니다.

자바 대기열
  • 무엇에 대해서
  • 차단 대기열
  • 블로킹 데크
자바 대기열

Java 대기열 클래스 메서드

Java 큐에는 매우 일반적으로 사용되는 메소드가 많이 있습니다. 대기열 인터페이스는 삽입, 삭제, 엿보기 등과 같은 다양한 방법을 촉진합니다. Java 대기열의 일부 작업은 예외를 발생시키는 반면 이러한 작업 중 일부는 프로그램이 완료될 때 특정 값을 반환합니다.

참고 - Java SE 8에서는 Java 대기열 컬렉션에 변경 사항이 없습니다. 에 정의된 이러한 메소드는 Java 프로그래밍 언어의 후속 버전에서 추가로 준비됩니다. 예를 들어 자바 SE 9입니다.

Java 대기열의 다양한 메소드가 아래에 정의되어 있습니다.

방법 방법 프로토타입 설명
추가하다 부울 추가(E e) 용량 제한을 위반하지 않고 대기열의 끝(꼬리)에 요소 e를 추가합니다. 성공하면 true를 반환하고, 용량이 소진되면 IllegalStateException을 반환합니다.
몰래 엿보다 이 엿보기() 대기열을 제거하지 않고 대기열의 선두(앞)를 반환합니다.
요소 E요소() peek() 메소드와 동일한 작업을 수행합니다. 대기열이 비어 있으면 NoSuchElementException이 발생합니다.
제거하다 E 제거() 대기열의 헤드를 제거하고 반환합니다. 대기열이 비어 있으면 NoSuchElementException이 발생합니다.
투표 전자설문() 대기열의 헤드를 제거하고 반환합니다. 대기열이 비어 있으면 null을 반환합니다.
권하다 부울 제안(E e) 용량 제한을 위반하지 않고 새 요소 e를 대기열에 삽입합니다.
크기 정수 크기() 대기열에 있는 요소의 크기 또는 수를 반환합니다.

Java 대기열 배열 구현

대기열 구현은 스택 구현만큼 간단하지 않습니다.

배열을 사용하여 큐를 구현하려면 먼저 n개의 요소를 보유하는 배열을 선언합니다.

그런 다음 이 대기열에서 수행할 다음 작업을 정의합니다.

자바 파일 열기

1) 대기열에 넣기: 큐에 요소를 삽입하는 작업은 Enqueue(프로그램의 함수 큐 Enqueue)입니다. 뒤쪽 끝에 요소를 삽입하려면 먼저 대기열이 꽉 찼는지 확인해야 합니다. 꽉 차 있으면 요소를 삽입할 수 없습니다. 후방인 경우

2) 꼬리: 대기열에서 요소를 삭제하는 작업은 Dequeue(프로그램의 함수 대기열 Dequeue)입니다. 먼저 대기열이 비어 있는지 확인합니다. 대기열 제거 작업이 작동하려면 대기열에 요소가 하나 이상 있어야 합니다.

3) 전면: 이 메서드는 대기열의 맨 앞 부분을 반환합니다.

자바 우선순위 큐

4) 디스플레이: 이 메서드는 대기열을 순회하고 대기열의 요소를 표시합니다.

Java 대기열 프로그램

다음 Java 프로그램은 Queue의 구현을 보여줍니다.

QueueArrayImplementation.java

 class Queue { private static int front, rear, capacity; private static int queue[]; Queue(int size) { front = rear = 0; capacity = size; queue = new int[capacity]; } // insert an element into the queue static void queueEnqueue(int item) { // check if the queue is full if (capacity == rear) { System.out.printf('
Queue is full
'); return; } // insert element at the rear else { queue[rear] = item; rear++; } return; } //remove an element from the queue static void queueDequeue() { // check if queue is empty if (front == rear) { System.out.printf('
Queue is empty
&apos;); return; } // shift elements to the right by one place uptil rear else { for (int i = 0; i <rear 0 4 - 1; i++) { queue[i]="queue[i" + 1]; } set queue[rear] to if (rear < capacity) decrement rear rear--; return; print queue elements static void queuedisplay() int i; (front="=" rear) system.out.printf('queue is empty
'); traverse front and for (i="front;" i rear; system.out.printf(' %d , ', queue[i]); of queuefront() system.out.printf('
front element the queue: %d', queue[front]); public class queuearrayimplementation main(string[] args) create a capacity q="new" queue(4); system.out.println('initial queue:'); q.queuedisplay(); inserting in q.queueenqueue(10); q.queueenqueue(30); q.queueenqueue(50); q.queueenqueue(70); system.out.println('queue after enqueue operation:'); q.queuefront(); insert q.queueenqueue(90); q.queuedequeue(); system.out.printf('
queue two dequeue operations:'); pre> <p> <strong>Output:</strong> </p> <pre> Initial Queue: Queue is Empty Queue after Enqueue Operation: 10 , 30 , 50 , 70 , Front Element of the queue: 10 Queue is full 10 , 30 , 50 , 70 , Queue after two dequeue operations: 50 , 70 , Front Element of the queue: 50 </pre> <h2>Java Queue Linked List Implementation</h2> <p>As we have implemented the Queue data structure using Arrays in the above program, we can also implement the Queue using Linked List.</p> <p>We will implement the same methods enqueue, dequeue, front, and display in this program. The difference is that we will be using the Linked List data structure instead of Array.</p> <p>The below program demonstrates the Linked List implementation of Queue in Java.</p> <p> <strong>QueueLLImplementation.java</strong> </p> <pre> class LinkedListQueue { private Node front, rear; private int queueSize; // queue size //linked list node private class Node { int data; Node next; } //default constructor - initially front &amp; rear are null; size=0; queue is empty public LinkedListQueue() { front = null; rear = null; queueSize = 0; } //check if the queue is empty public boolean isEmpty() { return (queueSize == 0); } //Remove item from the front of the queue. public int dequeue() { int data = front.data; front = front.next; if (isEmpty()) { rear = null; } queueSize--; System.out.println(&apos;Element &apos; + data+ &apos; removed from the queue&apos;); return data; } //Add data at the rear of the queue. public void enqueue(int data) { Node oldRear = rear; rear = new Node(); rear.data = data; rear.next = null; if (isEmpty()) { front = rear; } else { oldRear.next = rear; } queueSize++; System.out.println(&apos;Element &apos; + data+ &apos; added to the queue&apos;); } //print front and rear of the queue public void print_frontRear() { System.out.println(&apos;Front of the queue:&apos; + front.data + &apos; Rear of the queue:&apos; + rear.data); } } class QueueLLImplementation{ public static void main(String a[]){ LinkedListQueue queue = new LinkedListQueue(); queue.enqueue(6); queue.enqueue(3); queue.print_frontRear(); queue.enqueue(12); queue.enqueue(24); queue.dequeue(); queue.dequeue(); queue.enqueue(9); queue.print_frontRear(); } } </pre> <p> <strong>Output:</strong> </p> <pre> Element 6 added to the queue Element 3 added to the queue Front of the queue:6 Rear of the queue:3 Element 12 added to the queue Element 24 added to the queue Element 6 removed from the queue Element 3 removed from the queue Element 9 added to the queue Front of the queue:12 Rear of the queue:9 </pre> <hr></rear>

Java 대기열 연결 목록 구현

위 프로그램에서 배열을 사용하여 Queue 데이터 구조를 구현했으므로 Linked List를 사용하여 Queue를 구현할 수도 있습니다.

우리는 이 프로그램에서 enqueue, dequeue, front 및 display와 동일한 메소드를 구현할 것입니다. 차이점은 Array 대신 Linked List 데이터 구조를 사용한다는 것입니다.

아래 프로그램은 Java에서 대기열의 연결 목록 구현을 보여줍니다.

QueueLLImplementation.java

 class LinkedListQueue { private Node front, rear; private int queueSize; // queue size //linked list node private class Node { int data; Node next; } //default constructor - initially front &amp; rear are null; size=0; queue is empty public LinkedListQueue() { front = null; rear = null; queueSize = 0; } //check if the queue is empty public boolean isEmpty() { return (queueSize == 0); } //Remove item from the front of the queue. public int dequeue() { int data = front.data; front = front.next; if (isEmpty()) { rear = null; } queueSize--; System.out.println(&apos;Element &apos; + data+ &apos; removed from the queue&apos;); return data; } //Add data at the rear of the queue. public void enqueue(int data) { Node oldRear = rear; rear = new Node(); rear.data = data; rear.next = null; if (isEmpty()) { front = rear; } else { oldRear.next = rear; } queueSize++; System.out.println(&apos;Element &apos; + data+ &apos; added to the queue&apos;); } //print front and rear of the queue public void print_frontRear() { System.out.println(&apos;Front of the queue:&apos; + front.data + &apos; Rear of the queue:&apos; + rear.data); } } class QueueLLImplementation{ public static void main(String a[]){ LinkedListQueue queue = new LinkedListQueue(); queue.enqueue(6); queue.enqueue(3); queue.print_frontRear(); queue.enqueue(12); queue.enqueue(24); queue.dequeue(); queue.dequeue(); queue.enqueue(9); queue.print_frontRear(); } } 

산출:

 Element 6 added to the queue Element 3 added to the queue Front of the queue:6 Rear of the queue:3 Element 12 added to the queue Element 24 added to the queue Element 6 removed from the queue Element 3 removed from the queue Element 9 added to the queue Front of the queue:12 Rear of the queue:9