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

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

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

一、Thread 類

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

1、操作線程名稱的方法

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

  • public Thread(Runnable target,String name); 創(chuàng)建線程時(shí)設(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)建子類對(duì)象
    TestThread thread = new TestThread();

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

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

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

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

運(yùn)行結(jié)果:

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

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

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

獲取當(dāng)前線程對(duì)象名稱 :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)建出來(lái)的線程對(duì)象
    System.out.println(Thread.currentThread());

    // 獲取start()方法創(chuàng)建出來(lái)的線程對(duì)象名稱
    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()主線程對(duì)象名稱
    System.out.println(Thread.currentThread().getName());
  }
}

運(yùn)行結(jié)果:

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

相關(guān)文章

最新評(píng)論