Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Android

วิธีใช้ poll() ใน ConcurrentLinkedQueue ของ Android

ภาพรวมของ 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 extends
  • TextViewactionEvent → TextView actionEvent
  • ชื่อคลาส: ConcurrentLinkedQueue (ไม่ใช่ Deque)
  • เมธอด: poll() (ไม่ใช่ pool() - ตัวต้นฉบับเขียนผิด)

📝 หมายเหตุสำคัญ: poll() ไม่ใช่ pool()

❌ ข้อผิดพลาดใน tiêu đềต้นฉบับ: "pool()" → ✅ ถูกต้อง: "poll()"
pool() ไม่มีอยู่ใน Queue interface poll() = นำออกและคืนค่า (poll = โหวต/สำรวจ/นำออก)

poll() vs remove() vs peek()

เมธอดพฤติกรรมคิวว่างคืนค่า
poll()นำออกที่หัว + คืนค่าคืน nullE
remove()นำออกที่หัว + คืนค่าโยน NoSuchElementExceptionE
peek()ดูค่าที่หัว (ไม่ลบ)คืน nullE

วิธีทดสอบ

  1. รันแอป ดูคิว: [sai, ram, krishna, prasad, ram]
  2. คลิก TextView เรียก poll() → นำ "sai" ออก
  3. คลิกซ้ำจนคิวว่าง → ไม่ Crash แสดง [] ว่างเปล่า
  4. คลิกอีกครั้ง → ยังคงแสดง [] (poll() คืน null ไม่ทำอะไร)

กรณีใช้งานจริง

เหมาะสำหรับ Producer-Consumer pattern หลายเธรด Consumer เรียก poll() ได้พร้อมกันปลอดภัย ไม่ต้องกังวล Exception