1.定位最耗cpu进程
1.通过jps命令来查找对应的java线程
如果一个服务器上java进程很少,我们一眼就可以定位出这个线程。
77 jar
255 Jps
2.通过top命令来查找cpu使用最高的线程
如果一个服务器上有多个java服务,那么使用top命令对多个java进程进行观察,找出耗费cpu最大的进程,从下面可以看出是PID为77的进程最耗cpu
top - 14:21:59 up 36 min, 2 users, load average: 0.11, 0.13, 0.09
Tasks: 13 total, 1 running, 11 sleeping, 1 stopped, 0 zombie
%Cpu(s): 0.7 us, 3.9 sy, 0.0 ni, 95.2 id, 0.0 wa, 0.0 hi, 0.2 si, 0.0 st
KiB Mem : 2047036 total, 92068 free, 830284 used, 1124684 buff/cache
KiB Swap: 1048572 total, 1048492 free, 80 used. 1043460 avail Mem
PID USER PR NI VIRT RES SHR S %CPU %MEM TIME+ COMMAND
77 root 20 0 2818704 124676 16256 S 11.0 6.1 0:31.69 java
38 root 20 0 117704 9244 7820 S 4.3 0.5 0:28.41 sshd
12 root 20 0 33392 3872 2888 S 0.3 0.2 0:01.43 redis-server
2.定位最耗cpu线程
注意下面的pid是进程id
top -H -p <pid>
top -H -p 77
效果如下:可以看出来最耗cpu的线程是值为91的线程
top - 14:23:26 up 37 min, 2 users, load average: 0.02, 0.10, 0.08
Tasks: 13 total, 1 running, 11 sleeping, 1 stopped, 0 zombie
top - 14:23:59 up 38 min, 2 users, load average: 0.27, 0.15, 0.10
Threads: 14 total, 1 running, 13 sleeping, 0 stopped, 0 zombie
%Cpu(s): 0.9 us, 4.5 sy, 0.0 ni, 94.6 id, 0.0 wa, 0.0 hi, 0.0 si, 0.0 st
KiB Mem : 2047036 total, 91232 free, 831100 used, 1124704 buff/cache
KiB Swap: 1048572 total, 1048492 free, 80 used. 1042692 avail Mem
PID USER PR NI VIRT RES SHR S %CPU %MEM TIME+ COMMAND
91 root 20 0 2818704 125124 16256 R 11.3 6.1 0:30.25 java
77 root 20 0 2818704 125124 16256 S 0.0 6.1 0:00.00 java
78 root 20 0 2818704 125124 16256 S 0.0 6.1 0:02.49 java
79 root 20 0 2818704 125124 16256 S 0.0 6.1 0:00.04 java
使用 printf 函数打印出线程的16进制值(jvm里面使用的16进制来记录线程的线程号的)
printf %x 91
结果:
5b
3.通过jstack来定位这个线程
其中jstack是后面紧跟的值是进程的id,而后面grep命令后面紧跟的是我们线程的id
jstack <pid> | grep -C10 <tid>
jstack 77 | grep -C10 5b
结果如下:我们可以看到就是 32 行得到代码那边是最耗cpu的,我们就找到了这个耗cpu的代码具体位置了
"Attach Listener" #15 daemon prio=9 os_prio=0 tid=0x00007ffaec001000 nid=0x9f waiting on condition [0x0000000000000000]
java.lang.Thread.State: RUNNABLE
"DestroyJavaVM" #14 prio=5 os_prio=0 tid=0x00007ffb1c008800 nid=0x4e waiting on condition [0x0000000000000000]
java.lang.Thread.State: RUNNABLE
"t1" #12 prio=5 os_prio=0 tid=0x00007ffb1cd8b800 nid=0x5b waiting on condition [0x00007ffb09dbb000]
java.lang.Thread.State: TIMED_WAITING (sleeping)
at java.lang.Thread.sleep(Native Method)
at com.dada.test.arthastest.ArthasTestApplication$1.run(ArthasTestApplication.java:32)
at java.lang.Thread.run(Thread.java:745)
"Service Thread" #7 daemon prio=9 os_prio=0 tid=0x00007ffb1c140000 nid=0x57 runnable [0x0000000000000000]
java.lang.Thread.State: RUNNABLE
"C1 CompilerThread1" #6 daemon prio=9 os_prio=0 tid=0x00007ffb1c13d000 nid=0x56 waiting on condition [0x0000000000000000]
java.lang.Thread.State: RUNNABLE