Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Android

Cách thêm phần tử đầu vào ConcurrentLinkedDeque Android

Giới thiệu về ConcurrentLinkedDeque

ConcurrentLinkedDeque là deque không giới hạn dựa trên nút liên kết, hỗ trợ truy cập an toàn từ nhiều luồng. Yêu cầu API 21+.

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.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 phần tử mẫu
        concurrentLinkedDeque.add("sai");
        concurrentLinkedDeque.add("ram");
        concurrentLinkedDeque.add("krishna");
        concurrentLinkedDeque.add("prasad");

        actionEvent.setText(concurrentLinkedDeque.toString());

        actionEvent.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // Thêm phần tử vào đầu deque
                concurrentLinkedDeque.addFirst("phần tử đầu");
                actionEvent.setText(concurrentLinkedDeque.toString());
            }
        });
    }
}

Chạy ứng dụng

Kết nối thiết bị Android (API 21+) và chạy ứng dụng.

Cách thêm phần tử đầu vào ConcurrentLinkedDeque Android

Nhấn vào TextView để thêm phần tử đầu:

Cách thêm phần tử đầu vào ConcurrentLinkedDeque Android

Đặc điểm hiệu năng:
  • addFirst() và addLast() đều O(1)
  • Khác với ArrayDeque (không thread-safe), ConcurrentLinkedDeque dùng CAS (Compare-And-Swap) để đảm bảo an toàn luồng
  • Phù hợp cho hàng đợi công việc (work queue) trong môi trường đa luồng