ConcurrentLinkedQueue - clear()
clear() trên ConcurrentLinkedQueue xóa tất cả phần tử. Vì là cấu trúc linked-node non-blocking, nó duyệt và xóa từng node.
Code xử lý sự kiện click
actionEvent.setOnClickListener(v -> {
concurrentLinkedQueue.clear();
actionEvent.setText("Sau clear: " + concurrentLinkedQueue); // []
});
Toàn bộ 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.clear();
actionEvent.setText("Sau clear: " + concurrentLinkedQueue);
});
}
}
Lưu ý hiệu năng
clear() có độ phức tạp O(n). Trong môi trường đa luồng cao, các luồng khác vẫn có thể thêm phần tử ngay sau khi clear xong.