併發編程2.Thread核心方法

兩種線程實現方式沒有區別

java中,有實現Runnable接口和集成Thread類兩種實現線程的方式,但是在線程的運行過程中,這兩種實現方式並沒有區別,因爲在最終啓動線程時,都需要調用Thread類對象的start方法。

核心方式

currentThread

currentThread方法用於獲取當前正在執行的線程,即當前代碼段正在被哪個線程調用

Thread.currentThread()

isAlive

isAlive方法用於判斷當前線程是否處於存活狀態

public static void main(String[] args) throws Exception{

    Thread t = new Thread(()->{
        System.out.println( "線程內 " + Thread.currentThread().isAlive());
    });
    System.out.println( "啓動前 " + t.isAlive());
    t.start();
    System.out.println( "啓動後 " + t.isAlive());
    TimeUnit.SECONDS.sleep(1);
    System.out.println("最後 " + t.isAlive());
}

執行結果:
在這裏插入圖片描述

線程的優先級

在操作系統中,線程可以劃分優先級,CPU會優先執行優先級較高的線程對象中的任務,但是線程的優先級具有隨機性,並不是優先級高的線程就一定會先執行完

  • 設置線程的優先級
    Thread類中生命了三種線程的優先級
public final static int MIN_PRIORITY = 1;
public final static int NORM_PRIORITY = 5;
public final static int MAX_PRIORITY = 10;

調用setPriority方法設置優先級

new Thread().setPriority(Thread.MAX_PRIORITY);

守護線程

守護線程只有在有非守護線程運行的情況下才能存在,如果進程中沒有非守護線程了,守護線程也會自動銷燬

new Thread().setDaemon(true);

join

join方法表示等待被調用的線程執行完成之後,再執行自己
如在main方法中,啓動一個線程T,此時我們共啓動了兩個線程,T線程和main線程,要實現必須等T線程執行結束之後,才能讓main線程結束

public class ThreadJoin extends Thread{
    @Override
    public void run() {
        for (int i=0;i<5;i++){
            try {
                TimeUnit.MILLISECONDS.sleep(500);
                System.out.println(Thread.currentThread().getName() + " " + i);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        ThreadJoin t = new ThreadJoin();
        t.setName("T");
        t.start();
        try {
            t.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(Thread.currentThread().getName() + "執行結束");
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章