ภาพรวมของ ConcurrentLinkedQueue
ConcurrentLinkedQueue เป็นคิวแบบไม่มีขอบเขต (unbounded) บนโหนดเชื่อมโยง รองรับหลายเธรด (thread-safe) เรียงลำดับ FIFO (First-In-First-Out) เพิ่มที่ท้าย (tail) ไม่อนุญาตค่า null
ตัวอย่างการใช้งาน poll()
ตัวอย่างนี้สาธิตเมธอด poll() ซึ่งนำสมาชิกที่ หัว (head) ออกและคืนค่า คืน null หากคิวว่าง (ไม่โยน Exception)
ขั้นตอนที่ 1-2: สร้างโปรเจกต์และ Layout
สร้างโปรเจกต์ใหม่ ใช้ Layout TextView
ขั้นตอนที่ 3: โค้ด 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 { // แก้: MainActivityextends
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); // แก้: TextViewactionEvent
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(); // นำออกที่หัว คืน null ถ้าว่าง
actionEvent.setText("" + concurrentLinkedQueue);
}
});
}
}
🔧 การแก้ไขจากต้นฉบับ
MainActivityextends→MainActivity extendsTextViewactionEvent→TextView actionEvent- ชื่อคลาส:
ConcurrentLinkedQueue(ไม่ใช่ Deque) - เมธอด:
poll()(ไม่ใช่ pool() - ตัวต้นฉบับเขียนผิด)
📝 หมายเหตุสำคัญ: poll() ไม่ใช่ pool()
❌ ข้อผิดพลาดใน tiêu đềต้นฉบับ: "pool()" → ✅ ถูกต้อง: "poll()"
pool() ไม่มีอยู่ใน Queue interface poll() = นำออกและคืนค่า (poll = โหวต/สำรวจ/นำออก)
poll() vs remove() vs peek()
| เมธอด | พฤติกรรม | คิวว่าง | คืนค่า |
|---|---|---|---|
poll() | นำออกที่หัว + คืนค่า | คืน null | E |
remove() | นำออกที่หัว + คืนค่า | โยน NoSuchElementException | E |
peek() | ดูค่าที่หัว (ไม่ลบ) | คืน null | E |
วิธีทดสอบ
- รันแอป ดูคิว: [sai, ram, krishna, prasad, ram]
- คลิก TextView เรียก poll() → นำ "sai" ออก
- คลิกซ้ำจนคิวว่าง → ไม่ Crash แสดง [] ว่างเปล่า
- คลิกอีกครั้ง → ยังคงแสดง [] (poll() คืน null ไม่ทำอะไร)
กรณีใช้งานจริง
เหมาะสำหรับ Producer-Consumer pattern หลายเธรด Consumer เรียก poll() ได้พร้อมกันปลอดภัย ไม่ต้องกังวล Exception