官术网_书友最值得收藏!

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
主站蜘蛛池模板: 双辽市| 镇平县| 岑溪市| 新乡市| 云阳县| 巴楚县| 孝义市| 辛集市| 兴隆县| 万全县| 于田县| 东乌| 苗栗县| 永登县| 临武县| 光山县| 滁州市| 敦化市| 新源县| 安化县| 云霄县| 山西省| 南木林县| 鄂托克旗| 竹山县| 宜兴市| 志丹县| 普兰店市| 孝感市| 漾濞| 德化县| 铜鼓县| 井冈山市| 湘乡市| 千阳县| 张北县| 从化市| 万盛区| 伊金霍洛旗| 会同县| 云梦县|