一:測試運行代碼:
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