線程棧獲取java
/** * 線程棧和線程異常處理 * @author ydy * */ public class ThreadStackTest { public static void main(String[] args) { testStack(); } /** * 測試線程棧 * */ private static void testStack() { Thread currentThread = Thread.currentThread(); StackTraceElement[] stackTrace = currentThread.getStackTrace();//獲取線程棧中元素 for(StackTraceElement element:stackTrace) { String fileName = element.getFileName(); String methodName = element.getMethodName(); System.out.println("fileName:"+fileName); System.out.println("methodName:"+methodName); } } }
輸出結果apache
fileName:Thread.java methodName:getStackTrace fileName:ThreadStackTest.java methodName:testStack fileName:ThreadStackTest.java methodName:main
線程異常處理器 UncaughtExceptionHandlerbash
package com.ydy.thread; import java.lang.Thread.UncaughtExceptionHandler; import org.apache.commons.lang3.exception.ExceptionUtils; /** * 線程異常處理 * @author ydy * */ public class ThreadExceptionTest { public static void main(String[] args) { Runnable runnable=new Runnable() { @Override public void run() { // TODO Auto-generated method stub int i=1/0; } }; Thread thread=new Thread(runnable); thread.setUncaughtExceptionHandler(new UncaughtExceptionHandlerDefault()); thread.start(); } } class UncaughtExceptionHandlerDefault implements UncaughtExceptionHandler{ @Override public void uncaughtException(Thread t, Throwable e) { // TODO Auto-generated method stub System.out.println("異常線程名稱:"+t.getName()); System.out.println("異常信息:"+ExceptionUtils.getStackTrace(e)); } }
輸出信息ide
異常線程名稱:Thread-0 異常信息:java.lang.ArithmeticException: / by zero at com.ydy.thread.ThreadExceptionTest$1.run(ThreadExceptionTest.java:17) at java.lang.Thread.run(Thread.java:745)