Monitor Ctrl-Break線程這個在idea中特有的線程,你了解嗎?這線程可能會在你調試的時候給你帶來謎一樣的結果,為什么呢?請看下面的例子:
首先我們先復習一下多線程的狀態(因為這個問題是我在復習多線程的時候發現的問題)
對於線程的所有狀態該如何去查看呢?線程的狀態都是怎么產生的這些面試高頻題目,我們是否還記得呢?下面附上代碼用代碼再一次復習一下,簡單明了。
下面是全部的代碼:
1 /** 2 * @Description: 查看線程的所有狀態 3 * @ProjectName: demo 4 * @Package: com.thread 5 * @Author: XiaoHeMa 6 * @CreateDate: 2020/10/24 9:03 7 */ 8 9 public class ThreadSate { 10 11 12 13 public static void main(String[] args) { 14 15 Thread thread = new Thread(() -> { 16 17 for (int i = 0; i < 5; i++) { 18 19 try { 20 21 Thread.sleep(100); 22 23 } catch (InterruptedException e) { 24 25 e.printStackTrace(); 26 27 } 28 29 } 30 31 System.out.println("---thread線程結束---"); 32 33 }); 34 35 //查看線程的狀態 36 37 Thread.State state = thread.getState(); 38 39 //這時候我們只是創建了個線程 也就是NEW的狀態 40 41 System.out.println("線程狀態 " + state); 42 43 //啟動線程 44 45 thread.start(); 46 47 //查看線程的狀態 48 49 state = thread.getState(); 50 51 //這時候我們已經啟動了線程,然后來看看現在線程的狀態 RUNNABLE 52 53 System.out.println("線程狀態 " + state); 54 55 56 57 58 59 60 61 //根據線程的狀態來停止死循環 62 63 // while (state != Thread.State.TERMINATED) { 64 65 // try { 66 67 // Thread.sleep(200); 68 69 // } catch (InterruptedException e) { 70 71 // e.printStackTrace(); 72 73 // } 74 75 // //查看線程的狀態 76 77 // state = thread.getState(); 78 79 // System.out.println("線程狀態 " + state); 80 81 // } 82 83 84 85 86 87 //根據線程的總條數來停止死循環 88 89 while (true) { 90 91 int i = Thread.activeCount(); 92 93 System.out.println("目前線程數量:" + i); 94 95 /** 96 * Monitor Ctrl-Break這個線程只會在IDEA中被打印出來 97 * 在IDEA中通過debug啟動的不會出現,只有run啟動的會出現 98 * 所以在idea中執行run的時候這個要寫成2而不能是1在eclipse 99 * 中卻不會出現這個問題,這是軟件引起的在開發調試過程要注意。 100 */ 101 102 if (i == 2) { 103 104 break; 105 106 } 107 108 try { 109 110 Thread.sleep(200); 111 112 } catch (InterruptedException e) { 113 114 e.printStackTrace(); 115 116 } 117 118 //查看線程的狀態 119 120 state = thread.getState(); 121 122 System.out.println("線程狀態 " + state); 123 124 } 125 126 127 128 129 130 } 131 132 }
結果:
對於代碼中有檢驗的方式:一種是
Thread.State.TERMINATED
采用線程的狀態來判斷線程是否結束
另一種是通過線程的數量來判斷線程的數量
Thread.activeCount()
注意(使用idea的小伙伴要注意了,在idea中使用
Thread.activeCount()
debug啟動的不會出現,只有run啟動的會出現,出現線程數最后有2條的問題,所以在上面的代碼中才用
if (i == 2) { break; }
)
Monitor Ctrl-Break線程是在idea中才有的,而且還是要用run啟動方式,所以在寫測試代碼的小伙伴要注意了!!!
測試代碼
public class Main extends Thread { public static void main(String[] args) { Main t1 = new Main(); t1.setName("thread01"); t1.start(); ThreadGroup currentGroup = Thread.currentThread().getThreadGroup(); int noThreads = currentGroup.activeCount(); Thread[] lstThreads = new Thread[noThreads]; currentGroup.enumerate(lstThreads); for (int i = 0; i < noThreads; i++) { System.out.println("線程號:" + i + " = " + lstThreads[i].getName()); } } }