Java知多少(60)isAlive()和join()的使用
如前所述,通常你希望主线程最后结束。在前面的例子中,这点是通过在main()中调用sleep()来实现的,经过足够长时间的延迟以确保所有子线程都先于主线程结束。然而,这不是一个令人满意的解决方法,它也带来一个大问题:一个线程如何知道另一线程已经结束?幸运的是,Thread类提供了回答此问题的方法。
有两种方法可以判定一个线程是否结束。第一,可以在线程中调用isAlive()。这种方法由Thread定义,它的通常形式如下:
final boolean isAlive( )
如果所调用线程仍在运行,isAlive()方法返回true,如果不是则返回false。但isAlive()很少用到,等待线程结束的更常用的方法是调用join(),描述如下:
final void join( ) throws InterruptedException
该方法等待所调用线程结束。该名字来自于要求线程等待直到指定线程参与的概念。join()的附加形式允许给等待指定线程结束定义一个最大时间。下面是前面例子的改进版本。运用join()以确保主线程最后结束。同样,它也演示了isAlive()方法。
1 // Using join() to wait for threads to finish. 2 class NewThread implements Runnable { 3 String name; // name of thread 4 Thread t; 5 NewThread(String threadname) { 6 name = threadname; 7 t = new Thread(this, name); 8 System.out.println("New thread: " + t); 9 t.start(); // Start the thread 10 } 11 // This is the entry point for thread. 12 public void run() { 13 try { 14 for(int i = 5; i > 0; i--) { 15 System.out.println(name + ": " + i); 16 Thread.sleep(1000); 17 } 18 } catch (InterruptedException e) { 19 System.out.println(name + " interrupted."); 20 } 21 System.out.println(name + " exiting."); 22 } 23 } 24 25 class DemoJoin { 26 public static void main(String args[]) { 27 NewThread ob1 = new NewThread("One"); 28 NewThread ob2 = new NewThread("Two"); 29 NewThread ob3 = new NewThread("Three"); 30 System.out.println("Thread One is alive: "+ ob1.t.isAlive()); 31 System.out.println("Thread Two is alive: "+ ob2.t.isAlive()); 32 System.out.println("Thread Three is alive: "+ ob3.t.isAlive()); 33 // wait for threads to finish 34 try { 35 System.out.println("Waiting for threads to finish."); 36 ob1.t.join(); 37 ob2.t.join(); 38 ob3.t.join(); 39 } catch (InterruptedException e) { 40 System.out.println("Main thread Interrupted"); 41 } 42 System.out.println("Thread One is alive: "+ ob1.t.isAlive()); 43 System.out.println("Thread Two is alive: "+ ob2.t.isAlive()); 44 System.out.println("Thread Three is alive: "+ ob3.t.isAlive()); 45 System.out.println("Main thread exiting."); 46 } 47 }
程序输出如下所示:
New thread: Thread[One,5,main]
New thread: Thread[Two,5,main]
New thread: Thread[Three,5,main]
Thread One is alive: true
Thread Two is alive: true
Thread Three is alive: true
Waiting for threads to finish.
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
Two exiting.
Three exiting.
One exiting.
Thread One is alive: false
Thread Two is alive: false
Thread Three is alive: false
Main thread exiting.
如你所见,调用join()后返回,线程终止执行。