日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

currentThread()方法的作用

發布時間:2025/3/20 编程问答 25 豆豆
生活随笔 收集整理的這篇文章主要介紹了 currentThread()方法的作用 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

currentThread() 方法可返回代碼段正在被哪個線程調用的信息。下面通過一個示例進行說明。

例 1
假設在主線程中有如下代碼:

public class Run1 {public static void main(String[] args){//調用currentThread()方法輸出當前線程名稱System.out.println(Thread.currentThread().getName());} }

執行后在控制臺會輸出“main”,這說明 main() 方法被名為 main 的線程調用。

上例中 currentThread() 方法在主線程中,再來看一個在線程類中調用該方法的示例:

public class MyThread extends Thread {public MyThread(){ //調用currentThread()方法輸出當前線程名稱System.out.println("構造方法的打印:"+Thread.currentThread().getName()); } @Override public void run(){ //調用currentThread()方法輸出當前線程名稱System.out.println("run方法的打印:"+Thread.currentThread().getName()); } }

接下來編寫主線程代碼,創建 MyThread 線程實例并啟動線程。代碼如下:

public class Test {public static void main(String[] args){ MyThread threa=new MyThread();threa.start();} }

運行主線程將看到如下所示的結果。

構造方法的打印:main run方法的打印:Thread-0

從運行結果可以發現,MyThread 類的構造函數是被 main 線程調用的,而 run() 方法是被名稱為 Thread-0 的線程調用的,run() 方法是自動調用的方法。

對主線程的代碼進行簡單修改,使用“mythread.run()”代碼來啟動線程,此時的運行結果如下所示。

構造方法的打印:main run方法的打印:main

和之前的運行結果進行對比可以發現,此時 run() 方法的打印也是 main 線程調用的。

例 2
再來測試一個更復雜的情況

public class MyThread extends Thread {public MyThread(){ System.out.println("構造方法--開始");System.out.println("Thread.currentThread().getName()="+Thread.currentThread().getName());System.out.println("this.getName()="+this.getName());System.out.println("構造方法--結束");} @Override public void run(){ System.out.println("run()方法---開始"); System.out.println("Thread.currentThread().getName()="+Thread.currentThread().getName()); System.out.println("this.getName()="+this.getName()); System.out.println("run()方法---結束"); } }

如上述代碼所示,在 MyThread類的構造方法和 run() 方法中都調用了 currentThread() 方法。那么在啟動該線程時構造方法的線程名稱和 run() 方法中的線程名稱是否相同呢?帶著上面的疑問,我們來編寫一個主線程對 MyThread類進行測試。主線程代碼如下:

public class Test {public static void main(String[] args){ //創建MyThread線程實例MyThread myThread=new MyThread();//創建一個線程Thread t=new Thread(myThread);//設置線程名字t.setName("A");//啟動線程t.start();} }

執行后的輸出結果如下:

構造方法---開始 Thread.currentThread().getName()=main this.getName()=Thread-0 構造方法---結束 run()方法---開始 Thread.currentThread().getName()=A this.getName()=Thread-0 run()方法---結束

從結果可以發現,雖然 this.getName() 方法返回的都是 Thread-0,但是在構造方法中使用的即是 main 線程,而在 run() 方法中使用的是 A 線程。

總結

以上是生活随笔為你收集整理的currentThread()方法的作用的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。