1 import java.io.BufferedReader; 2 import java.io.InputStreamReader; 3 4 public class CPUTest { 5 public static void createBusyThread() { 6 Thread thread = new Thread(new Runnable() { 7 @Override 8 public void run() { 9 while (true) // 第41行 10 ; 11 } 12 }, "testBusyThread"); 13 thread.start(); 14 } 15 16 /** 17 * 線程鎖等待演示 18 */ 19 public static void createLockThread(final Object lock) { 20 Thread thread = new Thread(new Runnable() { 21 @Override 22 public void run() { 23 synchronized (lock) { 24 try { 25 lock.wait(); 26 } catch (InterruptedException e) { 27 e.printStackTrace(); 28 } 29 } 30 } 31 }, "testLockThread"); 32 thread.start(); 33 } 34 35 public static void main(String[] args) throws Exception { 36 BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); 37 br.readLine(); 38 createBusyThread(); 39 br.readLine(); 40 Object obj = new Object(); 41 createLockThread(obj); 42 } 43 }
這是源代碼。java
用命令top結果以下:ide
從上圖能夠看出進程6777CPU佔用率特別高,下面用命令top -p 6777 -H 查看具體是這個進程的哪一個線程佔用CPU高。spa
上圖可知是線程7003.線程好轉換成16進制,注意是小寫字母,0x1b5b。使用jstack 6777|grep -A 10 0x1b5b來查詢出具體的線程狀態線程
找到上邊代碼的第十行,發現是while循環一直運行。code