- Java多線程編程核心技術
- 高洪巖
- 453字
- 2019-01-01 01:10:25
1.3 currentThread()方法
currentThread()方法可返回代碼段正在被哪個線程調用的信息。下面通過一個示例進行說明。
創建t6項目,創建Run1.java類代碼如下:
public class Run1 { public static void main(String[] args) { System.out.println(Thread.currentThread().getName()); } }
程序運行結果如圖1-21所示。

圖1-21 運行結果
結果說明,main方法被名為main的線程調用。
繼續實驗,創建MyThread.java類。代碼如下:
public class MyThread extends Thread { public MyThread() { System.out.println("構造方法的打印:" + Thread.currentThread().getName()); } @Override public void run() { System.out.println("run方法的打印:" + Thread.currentThread().getName()); } }
運行類Run2.java代碼如下:
public class Run2 { public static void main(String[] args) { MyThread mythread = new MyThread(); mythread.start(); // mythread.run(); } }
程序運行結果如圖1-22所示。

圖1-22 運行結果
從圖1-22中的運行結果可以發現,MyThread.java類的構造函數是被main線程調用的,而run方法是被名稱為Thread-0的線程調用的,run方法是自動調用的方法。
文件Run2.java代碼更改如下:
public class Run2 { public static void main(String[] args) { MyThread mythread = new MyThread(); // mythread.start(); mythread.run(); } }
運行結果如圖1-23所示。

圖1-23 均被main主線程所調用
再來測試一個比較復雜的情況,創建測試用的項目currentThreadExt,創建Java文件CountOperate.java。代碼如下:
package mythread; public class CountOperate extends Thread { public CountOperate() { System.out.println("CountOperate---begin"); System.out.println("Thread.currentThread().getName()=" + Thread.currentThread().getName()); System.out.println("this.getName()=" + this.getName()); System.out.println("CountOperate---end"); } @Override public void run() { System.out.println("run---begin"); System.out.println("Thread.currentThread().getName()=" + Thread.currentThread().getName()); System.out.println("this.getName()=" + this.getName()); System.out.println("run---end"); } }
創建Run.java文件,代碼如下:
package test; import mythread.CountOperate; public class Run { public static void main(String[] args) { CountOperate c = new CountOperate(); Thread t1 = new Thread(c); t1.setName("A"); t1.start(); } }
程序運行結果如下:
CountOperate---begin Thread.currentThread().getName()=main this.getName()=Thread-0 CountOperate---end run---begin Thread.currentThread().getName()=A this.getName()=Thread-0 run---end
推薦閱讀
- C++ Primer習題集(第5版)
- Building Modern Web Applications Using Angular
- JavaScript 網頁編程從入門到精通 (清華社"視頻大講堂"大系·網絡開發視頻大講堂)
- FreeSWITCH 1.6 Cookbook
- Python Game Programming By Example
- INSTANT CakePHP Starter
- MySQL數據庫管理與開發實踐教程 (清華電腦學堂)
- 學習正則表達式
- Go語言精進之路:從新手到高手的編程思想、方法和技巧(1)
- Test-Driven Machine Learning
- PHP與MySQL權威指南
- Scala Functional Programming Patterns
- MySQL 8從零開始學(視頻教學版)
- Python Projects for Kids
- 體驗之道:從需求到實踐的用戶體驗實戰