知道线程何时结束是很有用的.例如,在前面的示例中,为了演示使主线程的存活时间长于其他线程的好处,就需要做到这一点.在这些程序中,这是通过让主线程的睡眠时间多于他创建的子线程来实现的.当然,这不能说是一个令人满意的或是可通用的解决方法.
幸运的是,Thread提供了两种方法,可以确定线程是否结束.第一种方法是可以在线程中调用isAlive(),其基本形式如下所示:
final boolean isAlive();
如果调用isAlive()方法的线程仍在运行,该方法就返回true,否则返回false.为使用isAlive(),更新代码:
public class test2 { // @param args public static void main(String args[]) { MyThread mt1 = new MyThread("child#1"); MyThread mt2 = new MyThread("child#2"); MyThread mt3 = new MyThread("child#3"); mt1.start(); mt2.start(); mt3.start(); do { System.out.print("."); try { Thread.sleep(100); }catch(InterruptedException exc) { System.out.println("main thread interrupted"); } } while(mt1.isAlive() || mt2.isAlive() || mt3.isAlive()); System.out.println("main thread ending"); } } class MyThread extends Thread implements Runnable { String thrdName; MyThread(String name) { thrdName = name; } public void run() { System.out.println(thrdName+" start"); try { for(int count=0;count<10;count++) { Thread.sleep(400); System.out.println(thrdName+" count is "+count); } }catch(InterruptedException exc) { System.out.println(thrdName+" interrupted"); } } }
该版本的输出与前面很相似,但是main()在其他线程结束后立即终止.另一个区别是他使用isAlive()来等待子线程结束.另一种等待线程结束的方法是调用join().如下所示:
final void join() throws InterruptedException
该方法将等待,直到他调用的线程终止.他的名字表示调用线程会一直等待,直到指定线程加入他,join()的另一种允许指定等待指定线程终止的最大时间.
下面是一个使用join()来确保主线程的最后结束的程序:
public static void main(String args[]) { MyThread mt1 = new MyThread("child#1"); MyThread mt2 = new MyThread("child#2"); MyThread mt3 = new MyThread("child#3"); mt1.start(); mt2.start(); mt3.start(); try { mt1.join(); //等待直到线程终结 mt2.join(); mt3.join(); System.out.println("mt 123 joined"); }catch(InterruptedException exc) { System.out.println("main thread interrupted"); } System.out.println("main thread ending"); }
输出如下所示:
child#1 start child#2 start child#3 start child#1 count is 0 child#3 count is 0 child#2 count is 0 child#3 count is 1 child#1 count is 1 child#2 count is 1 child#3 count is 2 child#1 count is 2 child#2 count is 2 child#1 count is 3 child#2 count is 3 child#3 count is 3 child#3 count is 4 child#1 count is 4 child#2 count is 4 child#1 count is 5 child#2 count is 5 child#3 count is 5 child#1 count is 6 child#3 count is 6 child#2 count is 6 child#1 count is 7 child#3 count is 7 child#2 count is 7 child#2 count is 8 child#1 count is 8 child#3 count is 8 child#1 count is 9 child#2 count is 9 child#3 count is 9 mt 123 joined main thread ending
如你所见,当对join()的调用返回后,线程已经停止执行.