前言
這次的題目講一個另一個多線程的關鍵字join,當使用join()的時候,當前線程會讓出執行權,讓join線程優先進行
題目
3個線程,打印出ACB
代碼
public class Test14A extends Thread{
public void run(){
System.out.println("A start");
System.out.println("A");
}
}
public class Test14B extends Thread{
Test14A test14A;
public void run(){
System.out.println("B start");
try {
test14A.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("B");
}
public Test14A getTest14A() {
return test14A;
}
public void setTest14A(Test14A test14A) {
this.test14A = test14A;
}
}
public class Test14C extends Thread{
Test14B test14B;
public void run(){
System.out.println("C start");
try {
test14B.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("C");
}
public Test14B getTest14B() {
return test14B;
}
public void setTest14B(Test14B test14B) {
this.test14B = test14B;
}
public static void main(String[] args) {
Test14C test14C = new Test14C();
Test14B test14B = new Test14B();
Test14A test14A = new Test14A();
test14C.setTest14B(test14B);
test14B.setTest14A(test14A);
test14C.start();
test14B.start();
test14A.start();
}
}
結果值
C start
A start
B start
A
B
C
也可以設置線程先sleep一段時間,這樣可以優先進行輸出,但是無論怎麼改變執行的順序,輸出的順序一定是ABC這樣,
因爲在C線程中B線程join了,而B線程中A線程join了,所以一定會在A線程執行之後再執行B再執行C這個的順序。可以按順序打印出ABC