Java ArrayBlockingQueue

Trong hướng dẫn này, chúng ta sẽ tìm hiểu về lớp ArrayBlockingQueue và các phương thức của nó với sự trợ giúp của các ví dụ.

Các ArrayBlockingQueuelớp của framework Java Collections cung cấp việc thực hiện hàng đợi chặn sử dụng một mảng.

Nó thực hiện giao diện Java BlockingQueue .

Tạo ArrayBlockingQueue

Để tạo một hàng đợi chặn mảng, chúng ta phải nhập java.util.concurrent.ArrayBlockingQueuegói.

Sau khi chúng tôi nhập gói, đây là cách chúng tôi có thể tạo một hàng đợi chặn mảng trong Java:

ArrayBlockingQueue<Type> animal = new ArrayBlockingQueue<>(int capacity);

Đây,

  • Type – the type of the array blocking queue
  • capacity – the size of the array blocking queue

Ví dụ,

// Creating String type ArrayBlockingQueue with size 5
ArrayBlockingQueue<String> animals = new ArrayBlockingQueue<>(5);

// Creating Integer type ArrayBlockingQueue with size 5
ArrayBlockingQueue<Integer> age = new ArrayBlockingQueue<>(5);

Lưu ý: Bắt buộc phải cung cấp kích thước của mảng.

Các phương thức của ArrayBlockingQueue

Các ArrayBlockingQueuelớp học cung cấp cho việc thực hiện tất cả các phương pháp trong BlockingQueuegiao diện.

Các phương thức này được sử dụng để chèn, truy cập và xóa các phần tử khỏi hàng đợi chặn mảng.

Ngoài ra, chúng ta sẽ tìm hiểu về hai phương pháp put()và take()hỗ trợ hoạt động chặn trong hàng đợi chặn mảng.

Hai phương thức này phân biệt hàng đợi chặn mảng với các hàng đợi điển hình khác.

Chèn phần tử

  • add() – Inserts the specified element to the array blocking queue. It throws an exception if the queue is full.
  • offer() – Inserts the specified element to the array blocking queue. It returns false if the queue is full.

Ví dụ,

import java.util.concurrent.ArrayBlockingQueue;

class Main {
    public static void main(String[] args) {
        ArrayBlockingQueue<String> animals = new ArrayBlockingQueue<>(5);

        // Using add()
        animals.add("Dog");
        animals.add("Cat");

        // Using offer()
        animals.offer("Horse");
        System.out.println("ArrayBlockingQueue: " + animals);
    }
}

Đầu ra

ArrayBlockingQueue: [Dog, Cat, Horse]

Phần tử truy cập

  • peek() – Returns an element from the front of the array blocking queue. It returns null if the queue is empty.
  • iterator() – Returns an iterator object to sequentially access elements from the array blocking queue. It throws an exception if the queue is empty. We must import the java.util.Iterator package to use it.

Ví dụ,

import java.util.concurrent.ArrayBlockingQueue;
import java.util.Iterator;

class Main {
    public static void main(String[] args) {
        ArrayBlockingQueue<String> animals = new ArrayBlockingQueue<>(5);

        // Add elements
        animals.add("Dog");
        animals.add("Cat");
        animals.add("Horse");
        System.out.println("ArrayBlockingQueue: " + animals);

        // Using peek()
        String element = animals.peek();
        System.out.println("Accessed Element: " + element);

        // Using iterator()
        Iterator<String> iterate = animals.iterator();
        System.out.print("ArrayBlockingQueue Elements: ");

        while(iterate.hasNext()) {
            System.out.print(iterate.next());
            System.out.print(", ");
        }
    }
}

Đầu ra

ArrayBlockingQueue: [Dog, Cat, Horse]
Accessed Element: Dog
ArrayBlockingQueue Elements: Dog, Cat, Horse,

Xóa các phần tử

  • remove() – Returns and removes a specified element from the array blocking queue. It throws an exception if the queue is empty.
  • poll() – Returns and removes a specified element from the array blocking queue. It returns null if the queue is empty.
  • clear() – Removes all the elements from the array blocking queue.

Ví dụ,

import java.util.concurrent.ArrayBlockingQueue;

class Main {
    public static void main(String[] args) {
        ArrayBlockingQueue<String> animals = new ArrayBlockingQueue<>(5);

        animals.add("Dog");
        animals.add("Cat");
        animals.add("Horse");
        System.out.println("ArrayBlockingQueue: " + animals);

        // Using remove()
        String element1 = animals.remove();
        System.out.println("Removed Element:");
        System.out.println("Using remove(): " + element1);

        // Using poll()
        String element2 = animals.poll();
        System.out.println("Using poll(): " + element2);

        // Using clear()
        animals.clear();
        System.out.println("Updated ArrayBlockingQueue: " + animals);
    }
}

Đầu ra

ArrayBlockingQueue: [Dog, Cat, Horse]
Removed Elements:
Using remove(): Dog
Using poll(): Cat
Updated ArrayBlockingQueue: []

Phương thức put () và take ()

Trong quy trình đa luồng, chúng ta có thể sử dụng put()và take()chặn hoạt động của một luồng để đồng bộ hóa nó với một luồng khác. Các phương thức này sẽ đợi cho đến khi chúng có thể được thực thi thành công.

phương thức put ()

Để thêm một phần tử vào cuối hàng đợi mảng, chúng ta có thể sử dụng put()phương thức này.

Nếu hàng đợi chặn mảng đã đầy, nó sẽ đợi cho đến khi có khoảng trống trong hàng đợi mảng để thêm một phần tử.

Ví dụ,

import java.util.concurrent.ArrayBlockingQueue;

class Main {
    public static void main(String[] args) {
        ArrayBlockingQueue<String> animals = new ArrayBlockingQueue<>(5);

       try {
        // Add elements to animals
           animals.put("Dog");
           animals.put("Cat");
           System.out.println("ArrayBlockingQueue: " + animals);
        }
        catch(Exception e) {
            System.out.println(e);
        }
    }
}

Đầu ra

ArrayBlockingQueue: [Dog, Cat]

Ở đây, put()phương thức có thể ném ra InterruptedExceptionnếu nó bị gián đoạn trong khi chờ đợi. Do đó, chúng ta phải đặt nó bên trong một khối try..catch .

phương thức take ()

Để trả về và xóa một phần tử từ phía trước của hàng đợi mảng, chúng ta có thể sử dụng take()phương thức này.

Nếu hàng đợi chặn mảng trống, nó sẽ đợi cho đến khi có các phần tử trong hàng đợi mảng bị xóa.

Ví dụ,

import java.util.concurrent.ArrayBlockingQueue;

class Main {
    public static void main(String[] args) {
        ArrayBlockingQueue<String> animals = new ArrayBlockingQueue<>(5);

       try {
           //Add elements to animals
           animals.put("Dog");
           animals.put("Cat");
           System.out.println("ArrayBlockingQueue: " + animals);

           // Remove an element
           String element = animals.take();
           System.out.println("Removed Element: " + element);
        }
        catch(Exception e) {
            System.out.println(e);
        }
    }
}

Đầu ra

ArrayBlockingQueue: [Dog, Cat]
Removed Element: Dog

Ở đây, take()phương thức sẽ ném ra một InterrupedExceptionnếu nó bị gián đoạn trong khi chờ đợi. Do đó, chúng ta phải đặt nó bên trong một try...catchkhối.

Các phương pháp khác

MethodsDecfscriptions
contains(element)Searches the array blocking queue for the specified element.If the element is found, it returns true, if not it returns false.
size()Returns the length of the array blocking queue.
toArray()Converts array blocking queue to an array and returns it.
toString()Converts the array blocking queue to string

Tại sao sử dụng ArrayBlockingQueue?

Các ArrayBlockingQueuemảng sử dụng các mảng làm bộ nhớ trong của nó.

Nó được coi là một bộ sưu tập an toàn theo chủ đề . Do đó, nó thường được sử dụng trong các ứng dụng đa luồng.

Giả sử, một luồng đang chèn các phần tử vào hàng đợi và một luồng khác đang xóa các phần tử khỏi hàng đợi.

Bây giờ, nếu luồng đầu tiên chậm hơn luồng thứ hai, thì hàng đợi chặn mảng có thể khiến luồng thứ hai đợi cho đến khi luồng đầu tiên hoàn thành các hoạt động của nó.









Gõ tìm kiếm nhanh...