兩種線程實現方式沒有區別
在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() + "執行結束");
}
}