ArrayBlockingQueue में peek() से हेड एलिमेंट देखना
ArrayBlockingQueue एक बाउंडेड, FIFO (फर्स्ट-इन-फर्स्ट-आउट) क्यू है जो ऐरे द्वारा समर्थित है। क्षमता निश्चित होती है। peek() हेड एलिमेंट रिटर्न करता है बिना हटाए।
चरण 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 - peek() डेमो
package com.example.myapplication;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import android.view.View;
import android.widget.TextView;
import java.util.concurrent.ArrayBlockingQueue;
public class MainActivity extends AppCompatActivity {
ArrayBlockingQueue<String> arrayBlockingQueue;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// क्षमता 50
arrayBlockingQueue = new ArrayBlockingQueue<>(50);
final TextView actionEvent = findViewById(R.id.actionEvent);
// एलिमेंट्स जोड़ें
arrayBlockingQueue.add("साई");
arrayBlockingQueue.add("राम");
arrayBlockingQueue.add("कृष्ण");
arrayBlockingQueue.add("प्रसाद");
actionEvent.setText("" + arrayBlockingQueue);
// क्लिक पर हेड एलिमेंट दिखाएं
actionEvent.setOnClickListener(v -> {
String head = arrayBlockingQueue.peek(); // null अगर खाली
actionEvent.setText("हेड: " + (head != null ? head : "क्यू खाली"));
});
}
}
ArrayBlockingQueue मुख्य मेथड्स:
| मेथड | विवरण | खाली क्यू पर |
|---|---|---|
peek() | हेड एलिमेंट देखें, हटाएं नहीं | null रिटर्न |
poll() | हेड एलिमेंट हटाकर रिटर्न | null रिटर्न |
element() | हेड एलिमेंट देखें | NoSuchElementException |
remove() | हेड एलिमेंट हटाकर रिटर्न | NoSuchElementException |
offer(e) | टेल में जोड़ें (ब्लॉक नहीं) | false अगर फुल |
put(e) | टेल में जोड़ें (ब्लॉक करता है) | स्पेस तक इंतजार |
थ्रेड-सेफ्टी:
ArrayBlockingQueue आंतरिक लॉक (ReentrantLock) का उपयोग करता है - मल्टी-थ्रेडेड प्रोड्यूसर-कंज्यूमर पैटर्न के लिए सुरक्षित।
आउटपुट
प्रारंभ: [साई, राम, कृष्ण, प्रसाद]
क्लिक के बाद: हेड: साई


नोट: UI थ्रेड पर ब्लॉकिंग ऑपरेशन (put(), take()) न करें।