Giới thiệu về ConcurrentLinkedDeque
ConcurrentLinkedDeque là một deque (hàng đợi hai đầu) không giới hạn dựa trên các nút liên kết (linked nodes). Đặc điểm nổi bật là nhiều luồng (thread) có thể truy cập các phần tử của deque một cách an toàn mà không cần đồng bộ hóa tường minh.
Ví dụ minh họa sử dụng phương thức size()
Ví dụ này trình bày cách sử dụng phương thức size() để lấy số lượng phần tử trong ConcurrentLinkedDeque trên Android.
Bước 1: Tạo dự án mới
Mở Android Studio, chọn File → New Project và điền đầy đủ thông tin để tạo dự án mới.
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:layout_height="match_parent"
android:orientation="vertical"
android:gravity="center"
tools:context=".MainActivity">
<TextView
android:id="@+id/actionEvent"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_marginTop="30dp"
android:textSize="40sp" />
</LinearLayout>
Ở đây chúng ta sử dụng một TextView để hiển thị các phần tử của ConcurrentLinkedDeque và kích thước của nó.
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.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ử vào deque
concurrentLinkedDeque.add("sai");
concurrentLinkedDeque.add("ram");
concurrentLinkedDeque.add("krishna");
concurrentLinkedDeque.add("prasad");
// Hiển thị toàn bộ deque
actionEvent.setText("" + concurrentLinkedDeque);
// Xử lý sự kiện click để hiển thị size()
actionEvent.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
actionEvent.setText("" + concurrentLinkedDeque.size());
}
});
}
}
Chạy ứng dụng
Kết nối thiết bị Android thật với máy tính. Trong Android Studio, mở file activity và nhấn biểu tượng Run trên thanh công cụ. Chọn thiết bị di động của bạn làm mục tiêu triển khai.
Màn hình ban đầu sẽ hiển thị toàn bộ deque: [sai, ram, krishna, prasad]
Khi click vào TextView, kết quả sẽ hiển thị kích thước: 4