天天看點

Thread.currentThread()和this的差別——《Java多線程程式設計核心技術》

前言:在閱讀《Java多線程程式設計核心技術》過程中,對書中程式代碼Thread.currentThread()與this的差別有點混淆,這裡記錄下來,加深印象與了解。

具體代碼如下:

1 public class MyThread09 extends Thread {
 2 
 3     public MyThread09() {
 4         System.out.println("MyThread09 Constructor begin");
 5         System.out.println("Thread.currentThread.getName()=" + Thread.currentThread().getName());
 6         System.out.println("this.getName()=" + this.getName());
 7         System.out.println("MyThread09 Constructor end");
 8     }
 9 
10     @Override
11     public void run() {
12         System.out.println("run begin");
13         System.out.println("Thread.currentThread.getName()=" + Thread.currentThread().getName());
14         System.out.println("this.getName()=" + this.getName());
15         System.out.println("run end");
16 
17     }
18 
19     public static void main(String[] args) {
20         MyThread09 thread = new MyThread09();
21 //        thread.setName("B");
22         Thread thread1 = new Thread(thread);
23         thread1.setName("A");
24         thread1.start();
25 }      

輸出結果如下:

Thread.currentThread()和this的差別——《Java多線程程式設計核心技術》

分析:

這裡将MyThread09的對象作為參數傳遞給Thread的構造函數,相當于将MyThread09線程委托給thread1去執行,了解這裡是非常重要的。

在MyThread09的構造函數中列印如下内容:

1 MyThread09 Constructor begin
2 Thread.currentThread.getName()=main
3 this.getName()=Thread-0
4 MyThread09 Constructor end      

第2行:目前線程名為main

第3行:this.getName()=Thread-0 

首先看Thread.currentThread方法源碼:

Thread.currentThread()和this的差別——《Java多線程程式設計核心技術》

該方法為native的靜态方法,傳回正在執行該段代碼的線程對象。

這裡MyThread09的構造函數是由main線程執行的,所有Thread.currentThread.getName()=main。

再看this.getName()=Thread-0.首先我們看Thread的構造函數源碼:

Thread.currentThread()和this的差別——《Java多線程程式設計核心技術》

在初始化線程對象的時候會預設為線程名指派,格式為“Thread-”的形式。這裡的this指的是目前對象,而目前對象就是MyThread09對象,是以列印Thread-0。

再看其run方法的列印日志:

1 run begin
2 Thread.currentThread.getName()=A
3 this.getName()=Thread-0
4 run end      

由于我們将MyThread09對象委托給thread1去執行的,是以此時Thread.currentThread.getName()=A,而此時this對象還是表示的MyThread09,是以this.getName()=Thread-0。

将21行注釋打開,運作結果如下:

1 MyThread09 Constructor begin
2 Thread.currentThread.getName()=main
3 this.getName()=Thread-0
4 MyThread09 Constructor end
5 run begin
6 Thread.currentThread.getName()=A
7 this.getName()=B
8 run end      

在MyThread09執行構造函數時,還未調用setName方法,是以this.getName()=Thread-0,在執行run方法時,已為其指派,是以this.getName()=B。

通過以上分析,可明确清楚Thread.currentThread和this的差別:

①Thread.currentThread表示目前代碼段正在被哪個線程調用的相關資訊。

②this表示的是目前對象,與Thread.currentThread有很大的差別。

by Shawn Chen,2018.12.5日,下午。

=========================================================

比你優秀的人比你還努力,你有什麼資格不去奮鬥!

__一個有理想的程式員。