执行方式
使用命令
./busy_thread.sh [pid] [显示最忙的n个线程]
例子1: 查看pid=1999的最忙的5个线程:
./busy_thread.sh 1999 5
例子2: 定时查看
watch -n1 ./busy_thread.sh 1999 5
#!/bin/bash
if [ $# -eq 0 ];then
echo "./busy_thread.sh [pid] [num_of_top_busy_thread]"
exit -1
fi
pid=$1
jstack_cmd=""
if [[ $JAVA_HOME != "" ]]; then
jstack_cmd="$JAVA_HOME/bin/jstack"
else
r=`which jstack 2>/dev/null`
if [[ $r != "" ]]; then
jstack_cmd=$r
else
echo "can not find jstack"
exit -2
fi
fi
#line=`top -H -o %CPU -b -n 1 -p $pid | sed '1,/^$/d' | grep -v $pid | awk 'NR==2'`
top -H -b -n 1 -p $pid | sed '1,/^$/d' | sed '1d;/^$/d' | grep -v $pid | sort -nrk9 |awk '{print $1" "$9}' | head -"$2" > .tid.tmp
for i in `seq 1 $2`
do
line=`sed -n "$i"p .tid.tmp`
tid_0x=`printf "%0x" $(echo "$line" | awk '{print $1}')`
t_name=`jstack $pid | grep $tid_0x | awk -F '#' '{print $1}'`
cpu=`echo "$line" | awk '{print $2}'`
echo "cpu: $cpu %, thread_name: $t_name"
done
rm -r .tid.tmp