欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Java线程编程中isAlive()和join()的使用详解

程序员文章站 2024-03-05 23:44:07
一个线程如何知道另一线程已经结束?thread类提供了回答此问题的方法。 有两种方法可以判定一个线程是否结束。第一,可以在线程中调用isalive()。这种方法由thre...

一个线程如何知道另一线程已经结束?thread类提供了回答此问题的方法。

有两种方法可以判定一个线程是否结束。第一,可以在线程中调用isalive()。这种方法由thread定义,它的通常形式如下:

  final boolean isalive( )

如果所调用线程仍在运行,isalive()方法返回true,如果不是则返回false。但isalive()很少用到,等待线程结束的更常用的方法是调用join(),描述如下:

  final void join( ) throws interruptedexception

该方法等待所调用线程结束。该名字来自于要求线程等待直到指定线程参与的概念。join()的附加形式允许给等待指定线程结束定义一个最大时间。下面是前面例子的改进版本。运用join()以确保主线程最后结束。同样,它也演示了isalive()方法。

// using join() to wait for threads to finish.
class newthread implements runnable {
  string name; // name of thread
  thread t;
  newthread(string threadname) {
    name = threadname;
    t = new thread(this, name);
    system.out.println("new thread: " + t);
    t.start(); // start the thread
  }
  // this is the entry point for thread.
  public void run() {
    try {
      for(int i = 5; i > 0; i--) {
        system.out.println(name + ": " + i);
        thread.sleep(1000);
      }
    } catch (interruptedexception e) {
      system.out.println(name + " interrupted.");
    }
    system.out.println(name + " exiting.");
  }
}

class demojoin {
  public static void main(string args[]) {
    newthread ob1 = new newthread("one");
    newthread ob2 = new newthread("two");
    newthread ob3 = new newthread("three");
    system.out.println("thread one is alive: "+ ob1.t.isalive());
    system.out.println("thread two is alive: "+ ob2.t.isalive());
    system.out.println("thread three is alive: "+ ob3.t.isalive());
    // wait for threads to finish
    try {
      system.out.println("waiting for threads to finish.");
      ob1.t.join();
      ob2.t.join();
      ob3.t.join();
    } catch (interruptedexception e) {
      system.out.println("main thread interrupted");
    }
    system.out.println("thread one is alive: "+ ob1.t.isalive());
    system.out.println("thread two is alive: "+ ob2.t.isalive());
    system.out.println("thread three is alive: "+ ob3.t.isalive());
    system.out.println("main thread exiting.");
  }
}

程序输出如下所示:

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()后返回,线程终止执行。