线上Java应用,在业务高峰期的时候经常出现CPU跑高,需要查看实时的线程占用cpu情况,下面是一个很好用的脚本,可以快速导出每个线程的占用CPU情况,结合jstack日志,排查到具体的线程类名。
#!/bin/sh
export LANG="zh_CN.UTF-8";
export LC_ALL="zh_CN.UTF-8";
LOG_FILE="/tmp/jkiller.log";
JSTACK_FILE="/tmp/jstack.log";
PID="$1";
shift;
i=0;
j="$1";
if [ -z "${j}" ]; then
j=5;
fi
ps -mp ${PID} -o THREAD,tid,time | sort -rn > ${LOG_FILE};
jstack ${PID} > ${JSTACK_FILE};
for LINE in `cat ${LOG_FILE}|gawk -F '-' '{print $4}'|gawk -F ' ' '{print $1}'`
do
i=$(($i+1));
if (($i>$j)); then
break;
fi;
XPID=`printf "%x\n" ${LINE}`;
echo -ne "\033[32m";
echo ${XPID};
echo -e "\033[34m";
grep -A 10 "0x${XPID}" ${JSTACK_FILE};
echo -e "\e[0m";
done;