ConcurrentLinkedQueue এবং poll() মেথড
ConcurrentLinkedQueue একটি থ্রেড-সেফ, অনবাউন্ডেড কিউ যা FIFO (First-In-First-Out) নীতি মেনে চলে। poll() মেথড শিরোনাম থেকে উপাদান সরিয়ে ফেরত দেয়; খালি থাকলে null ফেরত দেয় (এক্সেপশন নয়)।
উদাহরণ
ধাপ ১: নতুন প্রজেক্ট তৈরি করুন
ধাপ ২: লেআউট XML (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>
ধাপ ৩: জাভা কোড (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.ConcurrentLinkedQueue;
public class MainActivity extends AppCompatActivity {
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("" + concurrentLinkedQueue);
actionEvent.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// শিরোনাম থেকে উপাদান সরিয়ে ফেলুন
concurrentLinkedQueue.poll();
actionEvent.setText("" + concurrentLinkedQueue);
}
});
}
}
poll() vs remove() vs peek()
| মেথড | কাজ | খালি কিউতে |
|---|---|---|
poll() | শিরোনাম সরিয়ে ফেরত দেয় | null ফেরত দেয় |
remove() | শিরোনাম সরিয়ে ফেরত দেয় | NoSuchElementException |
peek() | শিরোনাম দেখায় (সরায় না) | null ফেরত দেয় |
বহু-থ্রেড পরিবেশে ব্যবহার
// প্রোডিউসার থ্রেড
new Thread(() -> {
for (int i = 0; i < 100; i++) {
queue.add("Item " + i);
}
}).start();
// কনসিউমার থ্রেড
new Thread(() -> {
while (true) {
String item = queue.poll();
if (item != null) {
process(item);
}
}
}).start();
নোট
আর্টিকেলের টাইটেলে "pool()" লেখা আছে যা টাইপো - সঠিক মেথড হল poll()।