Giới thiệu về ConcurrentLinkedQueue
ConcurrentLinkedQueue là queue không giới hạn (unbounded), an toàn cho đa luồng, dựa trên nút liên kết. Tuân theo FIFO, thêm vào đuôi (tail), lấy từ đầu (head). Không cho phép phần tử null. Phù hợp cho producer-consumer pattern hiệu năng cao.
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.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.TextView;
import java.util.concurrent.ConcurrentLinkedQueue;
public class MainActivity extends AppCompatActivity {
ConcurrentLinkedQueue<String> concurrentLinkedQueue;
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
concurrentLinkedQueue = new ConcurrentLinkedQueue<>();
final TextView actionEvent = findViewById(R.id.actionEvent);
// Thêm phần tử mẫu
concurrentLinkedQueue.add("sai");
concurrentLinkedQueue.add("ram");
concurrentLinkedQueue.add("krishna");
concurrentLinkedQueue.add("prasad");
concurrentLinkedQueue.add("ram"); // Cho phép trùng lặp
actionEvent.setText(concurrentLinkedQueue.toString());
actionEvent.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// Kiểm tra sự tồn tại của "prasad"
boolean contains = concurrentLinkedQueue.contains("prasad");
actionEvent.setText("Chứa 'prasad': " + contains);
}
});
}
}
Chạy ứng dụng
Kết nối thiết bị (API 21+) và chạy ứng dụng.

Nhấn vào TextView để kiểm tra:

Đặc điểm contains():Lưu ý: Với queue lớn và tìm kiếm thường xuyên, cân nhắc
- Độ phức tạp O(n) - duyệt tuyến tính toàn bộ queue
- Sử dụng
equals()để so sánh- Thread-safe: có thể gọi contains() trong khi luồng khác add/remove
- Không có index-based access (không có get(index))
- Phương thức khác:
remove(Object o)xóa lần xuất hiện đầu tiên, trả về booleanConcurrentHashMaphoặc cấu trúc dữ liệu có index.