一般来说:有两种方法可以知道线程的结束。一:可以在线程中调用isAlive();二:调用join()方法
一 线程中调用isAlive()方法,它的一般形式如下:final boolean isAlive();如果调用他的线程仍在运行,返回true,否则,返回false;
用法:NewThread th1 = new NewThread("Thread1");
th1.t.isAlive();
二 线程中调用join()方法,它的一般形式如下:
final void join() throws InterruptedException;这个方法一直在等待,直到调用他的线程终止。join还有另一种形式允许指定等待线程终止的最大时间。
用法:NewThread th1 = new NewThread("Thread1");
th1.t.join();
例子如下:
- package thread;
- public class NewThread implements Runnable{
- Thread t;
- String name="";
- NewThread(String name){
- this.name=name;
- t = new Thread(this,name);
- //t = new Thread();
- System.out.println("Child Thread:"+t);
- //t.run();
- t.start();
- }
- public void run()
- {
- try {
- for (int n = 5; n > 0; n--) {
- System.out.println(name+":" + n);
- Thread.sleep(1000);
- }
- } catch (Exception e) {
- // TODO: handle exception
- System.out.println(name+":"+"interrupted");
- }
- System.out.println("Exiting "+name+" thread");
- }
- }
- package thread;
- public class DemoJoin {
- /**
- * @param args
- */
- public static void main(String[] args) {
- // TODO Auto-generated method stub
- NewThread th1 = new NewThread("Thread1");
- NewThread th2 = new NewThread("Thread2");
- NewThread th3 = new NewThread("Thread3");
-
- System.out.println("Thread1 is Alive:"+th1.t.isAlive());
- System.out.println("Thread2 is Alive:"+th2.t.isAlive());
- System.out.println("Thread3 is Alive:"+th3.t.isAlive());
-
- try {
- System.out.println("Waiting for Thread finished");
- th1.t.join();
- th2.t.join();
- th3.t.join();
- } catch (Exception e) {
- // TODO: handle exception
- System.out.println("Main thread Interrupt");
- }
-
- System.out.println("Thread1 is Alive:"+th1.t.isAlive());
- System.out.println("Thread2 is Alive:"+th2.t.isAlive());
- System.out.println("Thread3 is Alive:"+th3.t.isAlive());
- System.out.println("Main Thread existing");
- }
- }
阅读(15455) | 评论(0) | 转发(2) |