Assumes you have got your JVM PID in environment variable JVM_PID e.g.
export JVM_PID=1234
Ok Here goes!
TOP_CPU_THREAD_ID=`top -H -p $JVM_PID -n 1 | head -n 8 | tail -n 1 |
sed -e 's/^[[:space:]]*//' | tr -s ' ' | cut -d' ' -f1 | xargs printf "%X"`
&& jcmd $JVM_PID Thread.print | grep -i $TOP_CPU_THREAD_ID
sed -e 's/^[[:space:]]*//' | tr -s ' ' | cut -d' ' -f1 | xargs printf "%X"`
&& jcmd $JVM_PID Thread.print | grep -i $TOP_CPU_THREAD_ID
Explanation
Assign to variable TOP_CPU_THREAD_ID the result of the commands between the backticks ` and `
TOP_CPU_THREAD_ID=
Get a snapshot of the CPU usage for threads owned by the JVM PID given
top -H -p $JVM_PID -n 1
Cut off the header and take the first line (most CPU usage)
head -n 8 | tail -n 1
Trim off leading whitespace
sed -e 's/^[[:space:]]*//'
Collapse multiple spaces into single spaces
tr -s ' '
Cut into columns using space as separator and keep the first column (thread ID)
cut -d' ' -f1
Convert to hexadecimal
xargs printf "%X"
Now, with the hex thread ID run jcmd from your JDK with command Thread.print
jcmd $JVM_PID Thread.print
Grep for the entry with the thread ID that is consuming the most CPU
grep -i $TOP_CPU_THREAD_ID