两个线程中没有父子关系。完成后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