ภาพรวมของ ArrayBlockingQueue
ArrayBlockingQueue เป็นคิวแบบมีขอบเขต (bounded) ใช้ Array เป็นโครงสร้างข้อมูล เรียงลำดับ FIFO สมาชิกแรกที่เพิ่มจะอยู่ยาวที่สุด สมาชิกสุดท้ายอยู่สั้นที่สุด ต้องกำหนดขนาด (capacity) ตอนสร้าง
ตัวอย่างการใช้งาน poll()
ตัวอย่างนี้สาธิตเมธอด poll() ใน ArrayBlockingQueue
ขั้นตอนที่ 1-2: สร้างโปรเจกต์และ Layout
สร้างโปรเจกต์ใหม่ ใช้ Layout TextView
ขั้นตอนที่ 3: โค้ด Java
package com.example.myapplication;
import android.annotation.SuppressLint;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.TextView;
import java.util.concurrent.ArrayBlockingQueue;
public class MainActivity extends AppCompatActivity { // แก้: MainActivityextends
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); // แก้: TextViewactionEvent
arrayBlockingQueue.add("sai");
arrayBlockingQueue.add("ram");
arrayBlockingQueue.add("krishna");
arrayBlockingQueue.add("prasad");
actionEvent.setText("" + arrayBlockingQueue);
actionEvent.setOnClickListener(new View.OnClickListener() {
@SuppressLint("SetTextI18n")
@Override
public void onClick(View v) {
// poll() คืนค่าที่นำออก (head element)
String removed = arrayBlockingQueue.poll();
actionEvent.setText("Removed: " + removed + " | Queue: " + arrayBlockingQueue);
}
});
}
}
🔧 การแก้ไขจากต้นฉบับ
MainActivityextends→MainActivity extendsTextViewactionEvent→TextView actionEvent- เพิ่ม Generic Type
<String> - ปรับโค้ดแสดงผลให้ชัดเจน: แสดงค่าที่ถูกนำออกพร้อมคิวที่เหลือ
- แก้ไขคำอธิบาย: "pool()" → "poll()"
ArrayBlockingQueue vs ConcurrentLinkedQueue
| คุณสมบัติ | ArrayBlockingQueue | ConcurrentLinkedQueue |
|---|---|---|
| โครงสร้าง | Array (Fixed size) | Linked Nodes |
| ขอบเขต | Bounded (ต้องกำหนด capacity) | Unbounded |
| Blocking operations | มี (put, take, offer timeout) | ไม่มี |
| Null elements | ไม่ 허용 | ไม่ 허용 |
| Performance | เร็วกว่า (cache friendly) | ช้ากว่า (object allocation) |
เมธอด poll() ใน ArrayBlockingQueue
- นำสมาชิกหัวออกและคืนค่า
- คืน
nullทันทีหากคิวว่าง (ไม่ block) - ต่างจาก
take()ที่จะ block จนกว่าจะมีข้อมูล
วิธีทดสอบ
- รันแอป ดูคิวเริ่มต้น: [sai, ram, krishna, prasad]
- คลิก TextView → แสดง "Removed: sai | Queue: [ram, krishna, prasad]"
- คลิกซ้ำ 4 ครั้ง จนคิวว่าง
- คลิกอีกครั้ง → แสดง "Removed: null | Queue: []"
เมื่อไรควรใช้ ArrayBlockingQueue
- ต้องการควบคุมหน่วยความจำ (fixed capacity)
- ต้องการ blocking operations (put/take) สำหรับ Producer-Consumer
- ประสิทธิภาพสำคัญ (array เร็วกว่า linked list)