使用isAlive()和join判断线程是否已结束,让主线程最后结束。
package study;
class NewThread implements Runnable{
String name;
Thread t;
NewThread(String threadname){
this.name = threadname;
t = new Thread(this, name);
System.out.println("New Thread:" + t);
startThread();
}
public void startThread(){
this.t.start();
}
public boolean CheckIsThreadAlive(){
boolean isAlive = t.isAlive();
System.out.println(name + "is Alive:" + isAlive);
return isAlive;
}
@Override
public void run() {
try {
for (int i = 5; i > 0; i--){
System.out.println(name + ": " + i);
Thread.sleep(100);
}
}
catch (InterruptedException e){
System.out.println(name + "Interrupted");
}
System.out.println(name + " exiting.");
}
}
public class test01 {
public static void main(String[] args){
System.out.println("Program Start:");
NewThread t1 = new NewThread("One");
NewThread t2 = new NewThread("Two");
NewThread t3 = new NewThread("Three");
t1.CheckIsThreadAlive();
t2.CheckIsThreadAlive();
t3.CheckIsThreadAlive();
try{
System.out.println("Waiting for threads to finish.");
t1.t.join();
t2.t.join();
t3.t.join();
}
catch (InterruptedException e){
System.out.println("Main thread Interrupted");
}
t1.CheckIsThreadAlive();
t2.CheckIsThreadAlive();
t3.CheckIsThreadAlive();
System.out.println(("Exiting Main thread."));
}
}