Java线程编程中isAlive()和join()的使用详解
一个线程如何知道另一线程已经结束?Thread类提供了回答此问题的方法。
有两种方法可以判定一个线程是否结束。第一,可以在线程中调用isAlive()。这种方法由Thread定义,它的通常形式如下:
finalbooleanisAlive()
如果所调用线程仍在运行,isAlive()方法返回true,如果不是则返回false。但isAlive()很少用到,等待线程结束的更常用的方法是调用join(),描述如下:
finalvoidjoin()throwsInterruptedException
该方法等待所调用线程结束。该名字来自于要求线程等待直到指定线程参与的概念。join()的附加形式允许给等待指定线程结束定义一个最大时间。下面是前面例子的改进版本。运用join()以确保主线程最后结束。同样,它也演示了isAlive()方法。
//Usingjoin()towaitforthreadstofinish.
classNewThreadimplementsRunnable{
Stringname;//nameofthread
Threadt;
NewThread(Stringthreadname){
name=threadname;
t=newThread(this,name);
System.out.println("Newthread:"+t);
t.start();//Startthethread
}
//Thisistheentrypointforthread.
publicvoidrun(){
try{
for(inti=5;i>0;i--){
System.out.println(name+":"+i);
Thread.sleep(1000);
}
}catch(InterruptedExceptione){
System.out.println(name+"interrupted.");
}
System.out.println(name+"exiting.");
}
}
classDemoJoin{
publicstaticvoidmain(Stringargs[]){
NewThreadob1=newNewThread("One");
NewThreadob2=newNewThread("Two");
NewThreadob3=newNewThread("Three");
System.out.println("ThreadOneisalive:"+ob1.t.isAlive());
System.out.println("ThreadTwoisalive:"+ob2.t.isAlive());
System.out.println("ThreadThreeisalive:"+ob3.t.isAlive());
//waitforthreadstofinish
try{
System.out.println("Waitingforthreadstofinish.");
ob1.t.join();
ob2.t.join();
ob3.t.join();
}catch(InterruptedExceptione){
System.out.println("MainthreadInterrupted");
}
System.out.println("ThreadOneisalive:"+ob1.t.isAlive());
System.out.println("ThreadTwoisalive:"+ob2.t.isAlive());
System.out.println("ThreadThreeisalive:"+ob3.t.isAlive());
System.out.println("Mainthreadexiting.");
}
}
程序输出如下所示:
Newthread:Thread[One,5,main] Newthread:Thread[Two,5,main] Newthread:Thread[Three,5,main] ThreadOneisalive:true ThreadTwoisalive:true ThreadThreeisalive:true Waitingforthreadstofinish. One:5 Two:5 Three:5 One:4 Two:4 Three:4 One:3 Two:3 Three:3 One:2 Two:2 Three:2 One:1 Two:1 Three:1 Twoexiting. Threeexiting. Oneexiting. ThreadOneisalive:false ThreadTwoisalive:false ThreadThreeisalive:false Mainthreadexiting.
如你所见,调用join()后返回,线程终止执行。
热门推荐
10 五一公司放假祝福语简短
11 追星女孩的祝福语简短
12 给长辈端午祝福语 简短
13 生日祝福语有诗意简短
14 团圆日祝福语简短
15 中秋商务祝福语简短最新
16 温暖文艺简短祝福语短句
17 男孩上学祝福语简短的
18 入住酒店文案祝福语简短