Giới thiệu về ConcurrentLinkedDeque
ConcurrentLinkedDeque là một deque không giới hạn (unbounded) dựa trên các nút liên kết. Đặc điểm quan trọng nhất là nó an toàn cho đa luồng (thread-safe) - nhiều luồng có thể truy cập các phần tử deque đồng thời mà không cần đồng bộ hóa bên ngoài.
Phương thức peekLast() trả về phần tử cuối cùng của deque mà không xóa nó. Trả về null nếu deque rỗng.
Ví dụ minh họa
Bước 1: Tạo project mới
Mở Android Studio, chọn File → New Project và điền các thông tin cần thiết.
Bước 2: Cấu hình layout (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: Code 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.ConcurrentLinkedDeque;
public class MainActivity extends AppCompatActivity {
ConcurrentLinkedDeque<String> concurrentLinkedDeque;
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
concurrentLinkedDeque = new ConcurrentLinkedDeque<>();
final TextView actionEvent = findViewById(R.id.actionEvent);
// Thêm các phần tử
concurrentLinkedDeque.add("sai");
concurrentLinkedDeque.add("ram");
concurrentLinkedDeque.add("krishna");
concurrentLinkedDeque.add("prasad");
actionEvent.setText("" + concurrentLinkedDeque);
actionEvent.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
actionEvent.setText("" + concurrentLinkedDeque.peekLast());
}
});
}
}
Chạy ứng dụng
Kết nối thiết bị Android, nhấn Run trong Android Studio. Màn hình ban đầu hiển thị: [sai, ram, krishna, prasad]
Click vào TextView sẽ hiển thị phần tử cuối: prasad
So sánh với LinkedBlockingDeque
| Đặc điểm | LinkedBlockingDeque | ConcurrentLinkedDeque |
|---|---|---|
| Giới hạn dung lượng | Có (optional bounded) | Không (unbounded) |
| Thread-safe | Có | Có (lock-free) |
| Hiệu năng đa luồng | Tốt | Tốt hơn (non-blocking) |
| Phù hợp cho | Producer-consumer có giới hạn | High-concurrency unbounded |