join关键字 测试:
public class TestJoin {
public static void main(String[] args) throws InterruptedException {
// TODO Auto-generated method stub
for (int i = 0; i < 3; i++) {
ThreadTest t1=new ThreadTest("A");
ThreadTest t2=new ThreadTest("B");
ThreadTest t3=new ThreadTest("C");
t1.start();
t3.start();
t1.join();
t3.join();
t2.start();
}
}
}
class ThreadTest extends Thread {
private String name;
public ThreadTest(String name){
this.name=name;
}
public void run(){
for(int i=1;i<=1;i++){
System.out.print(name);
}
}
}
打印测试结果为: ACBCABCAB
说明 A/C 由于加入了join关键字,一定先于B执行,而A/C顺序,看cpu调度,无法确定
当: join 关键字后置的时候
public class TestJoin {
public static void main(String[] args) throws InterruptedException {
// TODO Auto-generated method stub
for (int i = 0; i < 3; i++) {
ThreadTest t1=new ThreadTest("A");
ThreadTest t2=new ThreadTest("B");
ThreadTest t3=new ThreadTest("C");
t1.start();
t3.start();
t2.start();
t1.join();
t3.join();
}
}
}
class ThreadTest extends Thread {
private String name;
public ThreadTest(String name){
this.name=name;
}
public void run(){
for(int i=1;i<=1;i++){
System.out.print(name);
}
}
}
打印结果: ACBBCAACB
多数情况为正确的,但是有错误出现(BCA),说明join关键字使用的时候,应规范使用,放在本身start方法之后(紧挨着)最为妥当.