join 会阻塞当前线程,会强制完其自己的线程后,再释放当前线程的阻塞。
但是它并不阻塞其他线程。
输出结果是:
t1sleep start
t2sleep start
t2run
t1run
t2run
t1run
t1run
t2run
t1run
t2run
t1run
t1sleep end
mainend...
t2run
t2sleep end
但是它并不阻塞其他线程。
public class ThreadTest {
/**
* @param args
*/
public static void main(String[] args) {
Thread t1=new SleepThread("t1");
Thread t2=new SleepThread("t2");
t1.start();
t2.start();
try {
t1.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("mainend...");
}
}
public class SleepThread extends Thread{
private String t;
public SleepThread(String t){
this.t=t;
}
@Override
public void run() {
try {
System.out.println(t+"sleep start");
for(int i=0;i<5;i++){
Thread.sleep(1000);
System.out.println(t+"run");
}
System.out.println(t+"sleep end");
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}输出结果是:
t1sleep start
t2sleep start
t2run
t1run
t2run
t1run
t1run
t2run
t1run
t2run
t1run
t1sleep end
mainend...
t2run
t2sleep end
本文通过一个具体的Java示例程序详细解释了线程中join方法的作用及其如何影响主线程和其他线程的执行流程。join方法使主线程等待被join的线程执行完毕后再继续执行。
729

被折叠的 条评论
为什么被折叠?



