欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Java?Thread?類和Runnable?接口詳解

 更新時間:2022年08月10日 15:47:18   作者:姚青&  
這篇文章主要介紹了Java?Thread?類和Runnable接口詳解,文章圍繞主題展開詳細(xì)的內(nèi)容介紹,具有一定的參考價值,需要的朋友可以參考一下

一、Thread 類

了解如何使用Thread 類實現(xiàn)多線程之后,繼續(xù)學(xué)習(xí)Thread 類實現(xiàn)多線程之后的相關(guān)功能及方法。

1、操作線程名稱的方法

構(gòu)造方法(實現(xiàn) Runnable 接口時候使用)

  • public Thread(Runnable target,String name); 創(chuàng)建線程時設(shè)置線程名稱。

成員方法:

  • public final void setName(String name); 設(shè)置線程的名稱。
  • public final String getName(); 獲取線程的名稱。

Demo 代碼示例:

public class TestThread extends Thread{

@Override
public void run() {
    for (int i = 1; i <= 10; i++) {
        System.out.println("我正在編寫多線程代碼"+ i);
    }
}

//程序主線程 main 線程
public static void main(String[] args) {

    //創(chuàng)建子類對象
    TestThread thread = new TestThread();

    // 設(shè)置線程名稱
    thread.setName("姚青新創(chuàng)建的線程");

    //調(diào)用 start() 方法開啟線程
    thread.start();

    for (int i = 1; i <= 10; i++) {
        System.out.println("我正在學(xué)習(xí)多線程"+ i);
    }

	// 獲取線程名稱
    System.out.println(thread.getName());
   }
}

運行結(jié)果:

2、獲取當(dāng)前正在執(zhí)行的線程

public static Thread currentThread(); 返回當(dāng)前正在執(zhí)行的線程對象

獲取當(dāng)前線程對象:Thread.currentThread(); 

獲取當(dāng)前線程對象名稱 :Thread.currentThread().getName();

Demo代碼示例:

public class TestThread extends Thread{

@Override
public void run() {
    for (int i = 1; i <= 5; i++) {
        System.out.println("我正在編寫多線程代碼"+ i);
    }

    // 獲取start()方法創(chuàng)建出來的線程對象
    System.out.println(Thread.currentThread());

    // 獲取start()方法創(chuàng)建出來的線程對象名稱
    System.out.println(Thread.currentThread().getName());
}

public static void main(String[] args) {
    TestThread thread = new TestThread();
    thread.setName("姚青新創(chuàng)建的線程");
    thread.start();
    for (int i = 1; i <= 5; i++) {
        System.out.println("我正在學(xué)習(xí)多線程"+ i);
    }
    //System.out.println(thread.getName());

    // 獲取main()主線程對象名稱
    System.out.println(Thread.currentThread().getName());
  }
}

運行結(jié)果:

通過運行結(jié)果可以發(fā)現(xiàn),在控制臺上分別打印出了 “main”、“Thread[姚青新創(chuàng)建的線程,5,main]”、“姚青新創(chuàng)建的線程”,可以看出將新創(chuàng)建的線程對象和對象名稱以及主方法的線程名稱都打印出來了。
在使用這個方法的時候需要注意一點,該方法固定的寫法就是 Thread.currentThread(); 放在那個線程中執(zhí)行這個方法就是指定的那個線程。

相關(guān)文章

最新評論