java 中Thread.join()的使用方法
java中Thread.join()的使用方法
如果一个线程A执行了thread.join()语句,其含义是:当前线程A等待thread线程终止之后才从thread.join()返回。
importjava.util.concurrent.TimeUnit;
/**
*6-13
*/
publicclassJoin{
publicstaticvoidmain(String[]args)throwsException{
Threadprevious=Thread.currentThread();
for(inti=0;i<10;i++){
//每个线程拥有前一个线程的引用,需要等待前一个线程终止,才能从等待中返回
Threadthread=newThread(newDomino(previous),String.valueOf(i));
thread.start();
previous=thread;
}
TimeUnit.SECONDS.sleep(5);
System.out.println(Thread.currentThread().getName()+"terminate.");
}
staticclassDominoimplementsRunnable{
privateThreadthread;
publicDomino(Threadthread){
this.thread=thread;
}
publicvoidrun(){
try{
thread.join();
}catch(InterruptedExceptione){
}
System.out.println(Thread.currentThread().getName()+"terminate.");
}
}
}
执行结果:
mainterminate. 0terminate. 1terminate. 2terminate. 3terminate. 4terminate. 5terminate. 6terminate. 7terminate. 8terminate. 9terminate.
热门推荐
10 财运虎年祝福语简短语
11 单亲爸爸春节祝福语简短
12 狗狗上厕所训练
13 植物种植祝福语简短
14 翻译考试祝福语朋友简短
15 个人周年庆简短祝福语
16 狗狗怎么训练
17 分别祝福语简短搞笑英文
18 生日广州男生祝福语简短