Giới thiệu về ArrayBlockingQueue
ArrayBlockingQueue là hàng đợi (queue) bị giới hạn dung lượng, dựa trên mảng, tuân theo nguyên tắc FIFO (First-In-First-Out). Phần tử đầu tiên vào (head) tồn tại lâu nhất, phần tử cuối vào tồn tại ít nhất. Luồng an toàn (thread-safe), phù hợp cho pattern Producer-Consumer.
Bước 1: Tạo dự án mới
Mở Android Studio, chọn File → New Project, điền thông tin cần thiết.
Bước 2: Thiết kế giao diện (res/layout/activity_main.xml)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:app="https://schemas.android.com/apk/res-auto"
xmlns:tools="https://schemas.android.com/tools"
android:layout_width="match_parent"
android:gravity="center"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:orientation="vertical">
<TextView
android:id="@+id/actionEvent"
android:textSize="40sp"
android:layout_marginTop="30dp"
android:layout_width="wrap_content"
android:layout_height="match_parent" />
</LinearLayout>
Bước 3: Viết logic (src/MainActivity.java)
package com.example.myapplication;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.TextView;
import java.util.concurrent.ArrayBlockingQueue;
public class MainActivity extends AppCompatActivity {
ArrayBlockingQueue<String> arrayBlockingQueue;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Khởi tạo queue dung lượng 50
arrayBlockingQueue = new ArrayBlockingQueue<>(50);
final TextView actionEvent = findViewById(R.id.actionEvent);
// Thêm phần tử mẫu
arrayBlockingQueue.add("sai");
arrayBlockingQueue.add("ram");
arrayBlockingQueue.add("krishna");
arrayBlockingQueue.add("prasad");
actionEvent.setText(arrayBlockingQueue.toString());
actionEvent.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// Lấy phần tử đầu (head) KHÔNG xóa khỏi queue
String head = arrayBlockingQueue.peek();
actionEvent.setText("Head: " + head);
}
});
}
}
Chạy ứng dụng
Kết nối thiết bị và chạy ứng dụng.

Nhấn vào TextView để xem phần tử head:

Các phương thức lấy phần tử head:Lưu ý:
Phương thức Hành vi Trả về khi rỗng peek()Xem head, KHÔNG xóa nullelement()Xem head, KHÔNG xóa Ném NoSuchElementExceptionpoll()Lấy VÀ xóa head nullremove()Lấy VÀ xóa head Ném NoSuchElementExceptiontake()Lấy VÀ xóa head, CHỜ nếu rỗng Block cho đến khi có phần tử ArrayBlockingQueuecần chỉ định dung lượng tối đa khi tạo.add()ném exception khi đầy,offer()trả về false.