共计 2336 个字符,预计需要花费 6 分钟才能阅读完成。
模仿问题代码
结构一个死循环, 造成 CPU 使用率 100%。
> vim InfiniteLoop.java
public class InfiniteLoop {public static void main(String[] args) {
Runnable target;
Thread thread=new Thread(new Runnable() {
@Override
public void run() {
long i=0;
while (true){i++;}
}
});
thread.setName("rumenz");
thread.start();}
}
> javac InfiniteLoop.java
运行问题代码
> java InfiniteLoop
发现零碎 CPU 100%
> top
6076 root 20 0 7096732 18972 10648 S 100.0 0.1 7:42.51 java InfiniteLoop
失去过程号是
6076
依据 top 命令,发现 PID 为
6076
的 Java 过程占用 CPU 高达 100%,呈现故障。
找出具体的线程号
> top -Hp 6076
6096 root 20 0 7096732 18972 10648 R 99.7 0.1 9:09.92 java
失去线程号是
6096
将线程号转换成 16 进制
> printf "%x\n" 6096
17d0
万事具备, 开始应用 jstack
打印堆栈信息
> jstack 6076 | grep 17d0 -A 30
"rumenz" #10 prio=5 os_prio=0 tid=0x00007fe0580f9000 nid=0x17d0 runnable [0x00007fe04431d000]
java.lang.Thread.State: RUNNABLE
at InfiniteLoop$1.run(InfiniteLoop.java:11)
at java.lang.Thread.run(Thread.java:748)
"Service Thread" #9 daemon prio=9 os_prio=0 tid=0x00007fe0580e5800 nid=0x17ce runnable [0x0000000000000000]
java.lang.Thread.State: RUNNABLE
"C1 CompilerThread3" #8 daemon prio=9 os_prio=0 tid=0x00007fe0580c8000 nid=0x17cd waiting on condition [0x0000000000000000]
java.lang.Thread.State: RUNNABLE
"C2 CompilerThread2" #7 daemon prio=9 os_prio=0 tid=0x00007fe0580c6000 nid=0x17cc waiting on condition [0x0000000000000000]
java.lang.Thread.State: RUNNABLE
"C2 CompilerThread1" #6 daemon prio=9 os_prio=0 tid=0x00007fe0580c4000 nid=0x17cb waiting on condition [0x0000000000000000]
java.lang.Thread.State: RUNNABLE
"C2 CompilerThread0" #5 daemon prio=9 os_prio=0 tid=0x00007fe0580c1000 nid=0x17ca waiting on condition [0x0000000000000000]
java.lang.Thread.State: RUNNABLE
"Signal Dispatcher" #4 daemon prio=9 os_prio=0 tid=0x00007fe0580bf800 nid=0x17c9 runnable [0x0000000000000000]
java.lang.Thread.State: RUNNABLE
"Finalizer" #3 daemon prio=8 os_prio=0 tid=0x00007fe05808e800 nid=0x17c8 in Object.wait() [0x00007fe044b25000]
java.lang.Thread.State: WAITING (on object monitor)
at java.lang.Object.wait(Native Method)
- waiting on <0x000000076d408ed8> (a java.lang.ref.ReferenceQueue$Lock)
at java.lang.ref.ReferenceQueue.remove(ReferenceQueue.java:144)
- locked <0x000000076d408ed8> (a java.lang.ref.ReferenceQueue$Lock)
at java.lang.ref.ReferenceQueue.remove(ReferenceQueue.java:165)
at java.lang.ref.Finalizer$FinalizerThread.run(Finalizer.java:216)
at InfiniteLoop$1.run(InfiniteLoop.java:11)
, 提醒出代码 11 行, 查看源码发现有一个死循环。
总结解决 JAVA,CPU 100% 的问题
top
查找CPU 100%
的过程号pid
top -Hp pid
找出过程pid
下最占CPU
的线程号tid
printf "%x\n" tid
将tid
转换成十六进制16tid
jstack pid | grep 16tid -A 30
打印堆栈信息- 解决问题代码
关注微信公众号:【入门小站】,解锁更多知识点。
正文完