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

Cách sử dụng ConcurrentLinkedQueue trong Android

ConcurrentLinkedQueue là gì?

ConcurrentLinkedQueue là hàng đợi không giới hạn (unbounded), dựa trên nút liên kết (linked nodes), tuân thủ FIFO (First-In-First-Out). Nó an toàn cho đa luồng (thread-safe) nhờ thuật toán CAS (Compare-And-Swap) không khóa (non-blocking). Không cho phép phần tử null.

Ví dụ cơ bản

MainActivity.java

package com.example.myapplication;

import android.os.Build;
import android.os.Bundle;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import android.widget.TextView;
import java.util.concurrent.ConcurrentLinkedQueue;

public class MainActivity extends AppCompatActivity {

    private 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);

        concurrentLinkedQueue.add("sai");
        concurrentLinkedQueue.add("ram");
        concurrentLinkedQueue.add("krishna");
        concurrentLinkedQueue.add("prasad");
        concurrentLinkedQueue.add("ram");

        actionEvent.setText("Queue: " + concurrentLinkedQueue);
    }
}

Đặc điểm nổi bật

  • Hiệu suất cao trong môi trường đa luồng cạnh tranh cao.
  • Phù hợp cho producer-consumer pattern.
  • Không hỗ trợ null.