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

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

Kiểm tra hàng đợi rỗng với isEmpty()

isEmpty() trả về true nếu ConcurrentLinkedQueue không chứa phần tử nào. Đây là thao tác đọc an toàn luồng.

Code demo

actionEvent.setOnClickListener(v -> {
    boolean empty = concurrentLinkedQueue.isEmpty();
    actionEvent.setText("isEmpty: " + empty); // false (vì đã add 5 phần tử)
});

MainActivity.java đầy đủ

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 -> {
            actionEvent.setText("isEmpty: " + concurrentLinkedQueue.isEmpty());
        });
    }
}

Kết quả

Hiển thị isEmpty: false. Nếu gọi clear() rồi mới check sẽ ra true.