在看多線程的時候,看到這個知識點,感覺需要驗證一下。
一:線程自啟動
1.程序
1 package com.jun.it.thread; 2 3 public class MyThread extends Thread { 4 MyThread(){ 5 System.out.println("----------"); 6 System.out.println("name:"+Thread.currentThread().getName()); 7 System.out.println("isActive:"+Thread.currentThread().isAlive()); 8 System.out.println("thisName:"+this.getName()); 9 System.out.println("thisIsActive:"+this.isAlive()); 10 System.out.println("----------"); 11 } 12 public void run(){ 13 System.out.println("======================="); 14 System.out.println("name:"+Thread.currentThread().getName()); 15 System.out.println("isActive:"+Thread.currentThread().isAlive()); 16 System.out.println("thisName:"+this.getName()); 17 System.out.println("thisIsActive:"+this.isAlive()); 18 System.out.println("======================="); 19 } 20 }
測試類:
1 package com.jun.it.thread; 2 3 4 public class RunMyThread { 5 public static void main(String[] args) { 6 test1(); 7 // test2(); 8 } 9 /** 10 * 測試一 11 */ 12 public static void test1(){ 13 MyThread myThread=new MyThread(); 14 myThread.setName("AA"); 15 myThread.start(); 16 } 17 18 /** 19 * 測試二 20 */ 21 public static void test2(){ 22 MyThread myThread=new MyThread(); 23 Thread thread=new Thread(myThread); 24 thread.setName("BB"); 25 thread.start(); 26 } 27 }
2.效果:
3.總結
Thread.currentThread():表示當前的代碼正在被誰調用。
this:只能是當前的線程,在程序中,代表是myThread。
PS:
至於thread-0:每次新new的時候,在構造函數中,會定義默認的線程名。
二:線程被作為參數傳入Thread
1.程序
啟動測試2
2.效果
3.總結
根據上文的說法,this代表myThread,則說明,線程沒有開啟。
在這個示例中,外部線程在start后啟動,實際上調用的是內部線程的run方法開啟的。
Thread.currentThread()與this指向了不同的線程對象,Thread.currentThread()指向的是外部的線程,表示當前方法被外部線程thread調用;this指向內部線程myThread。