當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Java Java.lang.Thread.join()用法及代碼示例


描述

這個java.lang.Thread.join(long millis) 方法最多等待millis該線程死亡的毫秒數。超時為 0 意味著永遠等待。

聲明

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

public final void join(long millis) throws InterruptedException

參數

millis- 這是以毫秒為單位的等待時間。

返回值

此方法不返回任何值。

異常

InterruptedException- 如果任何線程中斷了當前線程。拋出此異常時清除當前線程的中斷狀態。

示例

下麵的例子展示了 java.lang.Thread.join() 方法的用法。

package com.tutorialspoint;

import java.lang.*;

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();
      
      // waits at most 2000 milliseconds for this thread to die.
      t.join(2000);
      System.out.println("after waiting for 2000 milliseconds...");
      System.out.print(t.getName());
      
      //checks if this thread is alive
      System.out.println(", status = " + t.isAlive());
   }
}

讓我們編譯並運行上麵的程序,這將產生以下結果 -

Thread-0, status = true
after waiting for 2000 milliseconds...
Thread-0, status = false

相關用法


注:本文由純淨天空篩選整理自 Java.lang.Thread.join() Method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。