前言
这次的题目讲一个另一个多线程的关键字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