ArrayBlockingQueue बेसिक उपयोग - थ्रेड-सेफ बाउंडेड क्यू
ArrayBlockingQueue एक निश्चित आकार का, FIFO, ब्लॉकिंग क्यू है जो ऐरे द्वारा समर्थित है। प्रोड्यूसर-कंज्यूमर पैटर्न के लिए आदर्श।
चरण 1: प्रोजेक्ट बनाएं
Android Studio: File → New Project।
चरण 2: लेआउट (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:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:id="@+id/actionEvent"
android:textSize="40sp"
android:layout_marginTop="30dp"
android:layout_width="wrap_content"
android:layout_height="match_parent" />
</LinearLayout>
चरण 3: MainActivity.java - बेसिक ऑपरेशन्स
package com.example.myapplication;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import android.widget.TextView;
import java.util.concurrent.ArrayBlockingQueue;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView actionEvent = findViewById(R.id.actionEvent);
ArrayBlockingQueue<String> arrayBlockingQueue = new ArrayBlockingQueue<>(50);
// एलिमेंट्स जोड़ें (offer/put/add)
arrayBlockingQueue.add("साई");
arrayBlockingQueue.add("राम");
arrayBlockingQueue.add("कृष्ण");
arrayBlockingQueue.add("प्रसाद");
actionEvent.setText("क्यू: " + arrayBlockingQueue);
}
}
मुख्य ऑपरेशन्स तुलना:
| ऑपरेशन | मेथड | फुल होने पर | खाली होने पर |
|---|---|---|---|
| इन्सर्ट | add(e) | IllegalStateException | - |
| इन्सर्ट | offer(e) | false रिटर्न | - |
| इन्सर्ट | put(e) | ब्लॉक (इंतजार) | - |
| इन्सर्ट | offer(e, timeout) | टाइमआउट तक इंतजार | - |
| रिमूव | remove() | - | NoSuchElementException |
| रिमूव | poll() | - | null रिटर्न |
| रिमूव | take() | - | ब्लॉक (इंतजार) |
| रिमूव | poll(timeout) | - | टाइमआउट तक इंतजार |
| इन्सपेक्ट | element() | - | NoSuchElementException |
| इन्सपेक्ट | peek() | - | null रिटर्न |
प्रोड्यूसर-कंज्यूमर उदाहरण:
// प्रोड्यूसर थ्रेड
new Thread(() -> {
try {
for (int i = 0; i < 10; i++) {
queue.put("Item " + i); // ब्लॉक अगर फुल
Thread.sleep(100);
}
} catch (InterruptedException e) { Thread.currentThread().interrupt(); }
}).start();
// कंज्यूमर थ्रेड
new Thread(() -> {
try {
while (true) {
String item = queue.take(); // ब्लॉक अगर खाली
process(item);
}
} catch (InterruptedException e) { Thread.currentThread().interrupt(); }
}).start();
आउटपुट
क्यू: [साई, राम, कृष्ण, प्रसाद]

नोट: UI थ्रेड पर put()/take() कभी न करें - ANR होगा।