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

Cách dùng offer() trong ConcurrentLinkedQueue Android

offer() trên ConcurrentLinkedQueue

Vì ConcurrentLinkedQueue là unbounded, offer(E e) luôn trả về true và không bao giờ block. Nó tương đương add() nhưng an toàn hơn cho code generic (interface Queue).

MainActivity.java

package com.example.myapplication;

import android.os.Build;
import android.os.Bundle;
import android.view.View;
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);

        actionEvent.setOnClickListener(v -> {
            concurrentLinkedQueue.offer("prasad"); // Thêm trùng lặp
            actionEvent.setText("Sau offer: " + concurrentLinkedQueue);
        });
    }
}

Đặc điểm

  • Non-blocking, hiệu năng cao.
  • Cho phép trùng lặp.
  • Không cho null.