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

วัตถุประสงค์ของเมธอด dumpStack() ใน Java

เมธอด dumpStack() เป็น static method ของคลาส Thread ใช้ พิมพ์/แสดง stack trace ของ thread ปัจจุบันไปที่ System.err วัตถุประสงค์หลักคือ สำหรับการดีบัก (debugging) ภายในเรียก printStackTrace() ของ Throwable ไม่โยน Exception

ไวยากรณ์

public static void dumpStack()

ตัวอย่าง: ใช้ dumpStack()

public class ThreadDumpStackTest {
    public static void main(String args[]) {
        Thread t = Thread.currentThread();
        t.setName("ThreadDumpStackTest");
        t.setPriority(1);
        System.out.println("Current Thread: " + t);
        int count = Thread.activeCount();
        System.out.println("Active threads: " + count);
        Thread threads[] = new Thread[count];
        Thread.enumerate(threads);
        for (int i = 0; i < count; i++) {
            System.out.println(i + ": " + threads[i]);
        }
        Thread.dumpStack(); // พิมพ์ stack trace
    }
}

ผลลัพธ์

Current Thread: Thread[ThreadDumpStackTest,1,main]
Active threads: 1
0: Thread[ThreadDumpStackTest,1,main]
java.lang.Exception: Stack trace
    at java.lang.Thread.dumpStack(Thread.java:1336)
    at ThreadDumpStackTest.main(ThreadDumpStackTest.java:14)

กรณีใช้งาน: Debugging แบบง่าย ไม่ต้องจับ Exception แค่ต้องการดู call stack ณ จุดนั้น