ภาพรวมของ ConcurrentLinkedDeque
ConcurrentLinkedDeque เป็น Deque แบบไม่มีขอบเขต (unbounded) ที่สร้างบนโหนดที่เชื่อมโยง (linked nodes) รองรับการเข้าถึงจากหลายเธรด (thread-safe) พร้อมกันอย่างปลอดภัย
ตัวอย่างการใช้งาน peekLast()
ตัวอย่างนี้สาธิตวิธีใช้เมธอด peekLast() ใน ConcurrentLinkedDeque บน Android
ขั้นตอนที่ 1: สร้างโปรเจกต์ใหม่
เปิด Android Studio ไปที่ File → New Project แล้วกรอกข้อมูลที่จำเป็น
ขั้นตอนที่ 2: เพิ่ม Layout XML
เพิ่มโค้ดใน res/layout/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:gravity="center"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:orientation="vertical">
<TextView
android:id="@+id/actionEvent"
android:textSize="40sp"
android:layout_marginTop="30dp"
android:layout_width="wrap_content"
android:layout_height="match_parent" />
</LinearLayout>
ขั้นตอนที่ 3: เพิ่มโค้ด Java
เพิ่มโค้ดใน src/MainActivity.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.ConcurrentLinkedDeque;
public class MainActivity extends AppCompatActivity {
ConcurrentLinkedDeque<String> concurrentLinkedDeque;
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
concurrentLinkedDeque = new ConcurrentLinkedDeque<>();
final TextView actionEvent = findViewById(R.id.actionEvent);
concurrentLinkedDeque.add("sai");
concurrentLinkedDeque.add("ram");
concurrentLinkedDeque.add("krishna");
concurrentLinkedDeque.add("prasad");
actionEvent.setText("" + concurrentLinkedDeque);
actionEvent.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
actionEvent.setText("" + concurrentLinkedDeque.peekLast());
}
});
}
}
คำอธิบายสำคัญ
peekLast()คืนค่าสมาชิกตัวสุดท้าย โดยไม่ลบออก คืนnullถ้า Deque ว่าง- ConcurrentLinkedDeque เหมาะสำหรับสภาพแวดล้อมหลายเธรด (multi-threaded) เนื่องจากเป็น thread-safe
- แตกต่างจาก LinkedBlockingDeque ที่มีขอบเขตตัวเลือก (bounded optional)
วิธีทดสอบ
- รันแอปบนอุปกรณ์จริงผ่าน Android Studio
- สังเกตหน้าจอเริ่มต้นแสดงรายการข้อมูลใน Deque
- คลิก TextView เพื่อดูค่าสุดท้ายจาก
peekLast()