多執行緒執行狀態 Java
1、普通建立子執行緒
程式碼片段:
public class Main {
public static void main(String[] args) {
MyThread t = new MyThread();
t.start();
System.out.println("我是主執行緒!");
}
}
class MyThread extends Thread {
public void run() {
System.out.println("我是一個子執行緒!我執行完畢了!");
}
}
顯示結果:
我是主執行緒!
我是一個子執行緒!我執行完畢了!
2、Join():等到子執行緒結束了主執行緒才執行
程式碼片段:
public class Main { public static void main(String[] args) throws InterruptedException { MyThread t = new MyThread(); t.start(); t.join(); System.out.println("我是主執行緒!"); } } class MyThread extends Thread { public void run() { System.out.println("我是一個子執行緒!我執行完畢了!"); } }
顯示結果:
我是一個子執行緒!我執行完畢了!
我是主執行緒!
3、Thread守護執行緒
java中執行緒分為兩種型別:使用者執行緒和守護執行緒。通過Thread.setDaemon(false)
設定為使用者執行緒;通過Thread.setDaemon(true)
設定為守護執行緒。如果不設定該屬性,預設為使用者執行緒。
程式碼片段:
public class Main { public static void main(String[] args) throws InterruptedException { MyThread t = new MyThread(); t.setDaemon(true); t.start(); System.out.println("我是主執行緒!"); } } class MyThread extends Thread { public void run() { System.out.println("我是一個子執行緒!我執行完畢了!"); } }
結果顯示:
我是主執行緒!
我是一個子執行緒!我執行完畢了!
使用者執行緒和守護執行緒的區別
使用者執行緒和守護執行緒都是執行緒,區別是Java虛擬機器在所有使用者執行緒dead後,程式就會結束。而不管是否還有守護執行緒還在執行,若守護執行緒還在執行,則會馬上結束。很好理解,守護執行緒是用來輔助使用者執行緒的,如公司的保安和員工,各司其職,當員工都離開後,保安自然下班了。
4、Thread.yield()
:暫停當前正在執行的執行緒物件,並執行其他執行緒
程式碼片段:
public class Main {
public static void main(String[] args) throws InterruptedException {
MyThread t = new MyThread("執行緒一");
MyThread t2 = new MyThread("執行緒二");
t.start();
t2.start();
System.out.println("我是主執行緒!");
}
}
class MyThread extends Thread {
public MyThread (String name) {
super(name);
}
public void run() {
for(int i = 0; i <= 50; i++) {
System.out.println(this.getName() + ":" + this.getId()+"||"+"i = " + i);
if(i == 10) {
this.yield();//暫停執行緒執行其他執行緒
}
}
}
}
結果顯示:
這個結果有很多種情況,可能在10的時候,暫停後執行緒一可能又拿到了cpu的執行權,接著執行11(執行緒一)。
5、執行緒優先順序Priority
程式碼片段:
public class Main {
public static void main(String[] args) throws InterruptedException {
MyThread t1 = new MyThread("執行緒一");
MyThread t2 = new MyThread("執行緒二");
t1.setPriority(1); //設定執行緒優先順序 範圍在1-10(超出會拋異常)
t2.setPriority(10);
t1.start();
t2.start();
System.out.println("我是主執行緒!");
}
}
class MyThread extends Thread {
public MyThread (String name) {
super(name);
}
public void run() {
System.out.println(this.getName());
}
}
顯示結果:
我是主執行緒!
執行緒二
執行緒一
注:因為給執行緒T1設定了t1.setPriority(1)
1的優先順序,而給執行緒T2設定了t2.setPriority(10)
10的優先順序,所以T2擁有較多的CPU執行權,所以先執行完畢;優先順序只可以設定1~10範圍,優先順序越高,獲取CPU執行權就越多,設定優先權都是建議性的讓cpu優先執行某個執行緒,所以設定優先權未必有效,如果設定優先順序超過了1~10的範圍,就會丟擲異常;
。。。