/** 方法一 */
public class CallStack {
    public static void printCallStatck() {
        Throwable ex = new Throwable();
        StackTraceElement[] stackElements = ex.getStackTrace();
        if (stackElements != null) {
            for (int i = 0; i < stackElements.length; i++) {
                System.out.print(stackElements[i].getClassName() + "/t");
                System.out.print(stackElements[i].getFileName() + "/t");
                System.out.print(stackElements[i].getLineNumber() + "/t");
                System.out.println(stackElements[i].getMethodName());
                System.out.println("-----------------------------------");
            }
        }
    }
}

/** 方法二 */
Exception e = new Exception("this is a log");
e.printStackTrace();

/** 方法三 */
Thread.currentThread().getStackTrace()

 

 

#!/bin/sh
pro_name=java #process name
keys=`ps -ef |grep "$pro_name" |grep -v "grep" | awk '{print $2}'`
nowdate=`date +%Y%m%d%H%M%S`
jstackpath="/usr/java/jdk1.6.0_07/bin/jstack"
cpulogpath="/home/"
for key in ${keys}
do
  cpulogpath_file="${cpulogpath}cpu_${nowdate}${key}.log"
  cpustackCmd="${jstackpath} -l ${key} >${cpulogpath_file}"
  echo "command: ${cpustackCmd}"
  eval $cpustackCmd
done