執行緒建立,狀態,以及上下文切換簡介
阿新 • • 發佈:2019-02-01
package my.thread.test1;
public class InitThread {
public static void main(String[] args) {
System.out.println("main執行緒下的子執行緒執行");
Thread t1 = new MyThread();
System.out.println(t1.getState());
t1.setName("child thread of main");
t1.start();
System.out.println(t1.getState());
Runnable r = new MyThread1();
//第二個子執行緒
Thread t2 = new Thread(r);
t2.start();
// t1 t2執行緒屬於main執行緒的子執行緒,該兩個執行緒屬於使用者執行緒還是守護執行緒,要取決於其父執行緒.
// 當然,也可以呼叫執行緒的thread.setdeamon來設定該屬性
// 執行緒的執行緒狀態可以通過 thread.getstate來獲取.
// 有 NEW RUNNABLE
// RUNNABLE是一個複合狀態,其有ready running子狀態
// blocked 一個執行緒發起了一個阻塞式IO或者試圖去獲取一個唄其他執行緒是有的鎖時,會處於該狀態
// waiting 無線等待其他執行緒執行特定操作的狀態
// timed_waiting 帶有時間限制的等待執行緒
// terminated 已經執行結束的執行緒狀態
// 當執行緒狀態由runnable 狀態轉換為 blocked或者其他除了new 以及 結束狀態的狀態時,都意味著上下文切換的產生
//上下文切換 : 上下文資訊(context,包括cpu的暫存器,程式計數器在某一時間點的內容等)
// 上下文切換 指的是 對執行緒的上下文資訊進行儲存和恢復的過程
}
}
/**
* 執行緒建立方式1.
* @author 蔡長盟
* @description
* @version 2017年7月26日
*/
class MyThread extends Thread {
//thread也繼承了runnable介面
//所以 繼承thread類,重寫run方法即可建立一個子執行緒...
public void run() {
System.out.println(Thread.currentThread().getName() + " thread is running");
}
}
class MyThread1 implements Runnable {
public void run() {
System.out.println(Thread.currentThread().getName() + " thread is running");
}
}