一:测试运行代码:
package com.wang;
public class Main {
public static void main(String[] args) {
System.out.print(1);
new Main().run();
}
public void run(){
int i=1;
for(;;){
for(;;){
i++;
}
}
}
}
二:在linux中运行这段代码:然后用top就会看到cpu高的进程id 6375
PID 1 | USER | 1 | PR | NI | VIRT | RES | SHR | S | %CPU | %MEM | TIME+ | COMMAND |
---|
6375 |
user1 |
1 |
20 |
0 |
2150964 |
25300 |
14880 |
S |
88.7 |
2.5 |
0:22.72 |
java |
三:查看进程中的线程 ps -mp 6375 -o THREAD,tid,time
USER | %CPU | PRI | SCNT | WCHAH | USER | SYSTEM | TID | TIME |
---|
user1 |
86.3 |
19 |
- |
- |
- |
- |
6379 |
00:05:16 |
四:转储线程快照
- (./jstack 6375 > 6375)这里的6375是线程id
- 可以看到三中线程消耗cpu最高的是6379 转化为16进制是18eb。然后看四
五:在四中产生的转储文件(如下)找18eb这个线程。线程的调用栈就是代码中的i++;
2016-11-01 05:49:59
Full thread dump Java HotSpot(TM) 64-Bit Server VM (25.111-b14 mixed mode):
"Attach Listener" #8 daemon prio=9 os_prio=0 tid=0x00007ffa44001000 nid=0x1900 waiting on condition [0x0000000000000000]
java.lang.Thread.State: RUNNABLE
"Service Thread" #7 daemon prio=9 os_prio=0 tid=0x00007ffa6c0ce000 nid=0x18f3 runnable [0x0000000000000000]
java.lang.Thread.State: RUNNABLE
"C1 CompilerThread1" #6 daemon prio=9 os_prio=0 tid=0x00007ffa6c0b1000 nid=0x18f2 waiting on condition [0x0000000000000000]
java.lang.Thread.State: RUNNABLE
"C2 CompilerThread0" #5 daemon prio=9 os_prio=0 tid=0x00007ffa6c0af000 nid=0x18f1 waiting on condition [0x0000000000000000]
java.lang.Thread.State: RUNNABLE
"Signal Dispatcher" #4 daemon prio=9 os_prio=0 tid=0x00007ffa6c0ad800 nid=0x18f0 runnable [0x0000000000000000]
java.lang.Thread.State: RUNNABLE
"Finalizer" #3 daemon prio=8 os_prio=0 tid=0x00007ffa6c07a000 nid=0x18ef in Object.wait() [0x00007ffa5c6fd000]
java.lang.Thread.State: WAITING (on object monitor)
at java.lang.Object.wait(Native Method)
- waiting on <0x00000000f0c08e98> (a java.lang.ref.ReferenceQueue$Lock)
at java.lang.ref.ReferenceQueue.remove(ReferenceQueue.java:143)
- locked <0x00000000f0c08e98> (a java.lang.ref.ReferenceQueue$Lock)
at java.lang.ref.ReferenceQueue.remove(ReferenceQueue.java:164)
at java.lang.ref.Finalizer$FinalizerThread.run(Finalizer.java:209)
"Reference Handler" #2 daemon prio=10 os_prio=0 tid=0x00007ffa6c075800 nid=0x18ee in Object.wait() [0x00007ffa5c7fe000]
java.lang.Thread.State: WAITING (on object monitor)
at java.lang.Object.wait(Native Method)
- waiting on <0x00000000f0c06b40> (a java.lang.ref.Reference$Lock)
at java.lang.Object.wait(Object.java:502)
at java.lang.ref.Reference.tryHandlePending(Reference.java:191)
- locked <0x00000000f0c06b40> (a java.lang.ref.Reference$Lock)
at java.lang.ref.Reference$ReferenceHandler.run(Reference.java:153)
"main" #1 prio=5 os_prio=0 tid=0x00007ffa6c009800 nid=0x18eb runnable [0x00007ffa73870000]
java.lang.Thread.State: RUNNABLE
at com.wang.Main.run(Main.java:11)
at com.wang.Main.main(Main.java:6)
"VM Thread" os_prio=0 tid=0x00007ffa6c06e000 nid=0x18ed runnable
"VM Periodic Task Thread" os_prio=0 tid=0x00007ffa6c0d1800 nid=0x18f4 waiting on condition
JNI global references: 9