中有两个线程没有父子关系。 ParentThread
完成后,ParentThread
不会等待 ChildThread
。
public class MainThread {
public static void main(String[] args) {
ParentThread pt=new ParentThread();
pt.start();
for(int i=1;i<=20;i++){
System.out.println("ParentThread alive: "+pt.isAlive());
try{
Thread.currentThread().sleep(500);
}catch(Exception ex){
ex.printStackTrace();
}
}
}
}
class ParentThread extends Thread{
public void run(){
ChildThread ct=new ChildThread();
ct.start();
for(int i=1;i<=10;i++){
try{
System.out.println("ChildThread alive: "+ ct.isAlive() + ", i = "+i);
sleep(500);
}catch(Exception ex){
ex.printStackTrace();
}
}
}
}
class ChildThread extends Thread{
public void run(){
for(int i=1;i<=20;i++){
try{
System.out.println("ChildThread i = "+i);
sleep(500);
}catch(Exception ex){
ex.printStackTrace();
}
}
}
}
输出(像):
ParentThread alive: true
ChildThread alive: true, i = 1
ChildThread i = 1
ParentThread alive: true
ChildThread i = 2
ChildThread alive: true, i = 2
ParentThread alive: true
ChildThread i = 3
ChildThread alive: true, i = 3
ParentThread alive: true
ChildThread i = 4
ChildThread alive: true, i = 4
ParentThread alive: true
ChildThread i = 5
ChildThread alive: true, i = 5
ParentThread alive: true
ChildThread i = 6
ChildThread alive: true, i = 6
ParentThread alive: true
ChildThread alive: true, i = 7
ChildThread i = 7
ParentThread alive: true
ChildThread i = 8
ChildThread alive: true, i = 8
ParentThread alive: true
ChildThread alive: true, i = 9
ChildThread i = 9
ParentThread alive: true
ChildThread alive: true, i = 10
ChildThread i = 10
ParentThread alive: true
ChildThread i = 11
ParentThread alive: false
ChildThread i = 12
ChildThread i = 13
ParentThread alive: false
ParentThread alive: false
ChildThread i = 14
ParentThread alive: false
ChildThread i = 15
ParentThread alive: false
ChildThread i = 16
ParentThread alive: false
ChildThread i = 17
ChildThread i = 18
ParentThread alive: false
ParentThread alive: false
ChildThread i = 19
ParentThread alive: false
ChildThread i = 20
我想你问错了问题。在Java中查找setDemon的功能。 –
在这里看看这个问题:http://stackoverflow.com/questions/9939076/wait-until-child-threads-completed-java – mwhs
我已经搜索了关于这个话题!我问了这个问题,因为我认为这对其他人也是有用的,另一方面,在我对线程的看法上我错了。 @SotiriosDelimanolis – Johnny