JAVA 线程 join

来源:互联网 发布:windows内核编程 编辑:程序博客网 时间:2024/06/07 08:30
class Test5{


public static void main(String str[]) throws Exception{




class R implements Runnable {

private boolean b = true;
public void run(){
try{
//Thread.sleep(1000);
this.b = false;
}catch(Exception e){}
}


public boolean isB(){
return this.b;
}
}


R r = new R();
Thread t = new Thread(r);

System.out.println(111111);
t.start();
Thread.sleep(3000);
if(r.isB()){
System.out.println("未改变");
}else {
System.out.println("改变了");
}

t.join();


if(r.isB()){
System.out.println("未改变");
}else {
System.out.println("改变了");
}


}

}

如果红色代码要等待t实例的线程执行完成后,才能执行,则红色部分一定要放在蓝色后面。

PS:绿色的部分的执行结果不可预测,和t实例的线程执行时间有关(个人观点);


join:让当先线程等待被掉join的线程对象的线程执行完成后,才继续执行。