Java 线程 join() 方法



描述

Java Thread join() 方法等待此线程终止。

声明

以下是 java.lang.Thread.join() 方法的声明

public final void join() throws InterruptedException

参数

返回值

此方法不返回值。

异常

InterruptedException - 如果任何线程中断当前线程。当抛出此异常时,当前线程的中断状态将被清除。

示例:使线程等待

以下示例演示了 Java Thread join() 方法的使用。在此程序中,我们通过实现 Runnable 接口创建了一个线程类 ThreadDemo。在构造函数中,使用 currentThread() 方法检索当前线程。打印其名称并使用 isAlive() 检查线程是否处于活动状态。

在 main 方法中,我们使用 ThreadDemo 创建了一个线程,并使用 start() 方法启动线程。现在使用 join() 使线程等待终止,然后打印线程名称,并再次使用 isAlive() 打印其是否处于活动状态。

package com.tutorialspoint;

public class ThreadDemo implements Runnable {

   public void run() {

      Thread t = Thread.currentThread();
      System.out.print(t.getName());
      
      //checks if this thread is alive
      System.out.println(", status = " + t.isAlive());
   }

   public static void main(String args[]) throws Exception {

      Thread t = new Thread(new ThreadDemo());
      
      // this will call run() function
      t.start();
	  
      t.join();
      System.out.print(t.getName());
      
      //checks if this thread is alive
      System.out.println(", status = " + t.isAlive());
   }
} 

输出

让我们编译并运行上述程序,这将产生以下结果:

Thread-0, status = true
Thread-0, status = false
java_lang_thread.htm
广告

© . All rights reserved.