Java Thread.join()具有什么功能呢?
下文笔者讲述java中Thread.join()的功能简介说明,如下所示:
Thread.join()方法的功能: 用于等待进程 如:主线程创建子线程 当子线程运行时间非常长时,主线程通常会在子线程之前结束, 当主线程需等待子线程的处理结果时,此时我们需要使用join()方法
Thread.join()方法的语法
//无参数的join()等价于join(0),作用是一直等待该线程死亡 join() throws InterruptedException; //最多等待该线程死亡millis毫秒 join(long millis, int nanos) throws InterruptedException; //最多等待该线程死亡millis毫秒加nanos纳秒 join(long millis, int nanos) throws InterruptedException ;例
package com.java265.other; public class Test3 { public static void main(String[] args) { String threadName = Thread.currentThread().getName(); System.out.println(threadName + " start."); BThread bt = new BThread(); AThread at = new AThread(bt); try { bt.start(); Thread.sleep(2000); at.start(); at.join(); } catch (Exception e) { System.out.println("Exception from main"); } System.out.println(threadName + " end!"); } } class BThread extends Thread { public BThread() { super("[BThread] Thread"); }; public void run() { String threadName = Thread.currentThread().getName(); System.out.println(threadName + " start."); try { for (int i = 0; i < 6; i++) { System.out.println(threadName + " loop at " + i); Thread.sleep(1000); } System.out.println(threadName + " end."); } catch (Exception e) { System.out.println("Exception from " + threadName + ".run"); } } } class AThread extends Thread { BThread bt; public AThread(BThread bt) { super("[AThread] Thread"); this.bt = bt; } public void run() { String threadName = Thread.currentThread().getName(); System.out.println(threadName + " start."); try { bt.join(); System.out.println(threadName + " end."); } catch (Exception e) { System.out.println("Exception from " + threadName + ".run"); } } } ------运行以上代码,将输出以下信息------ main start. [BThread] Thread start. [BThread] Thread loop at 0 [BThread] Thread loop at 1 [BThread] Thread loop at 2 [AThread] Thread start. [BThread] Thread loop at 3 [BThread] Thread loop at 4 [BThread] Thread loop at 5 [BThread] Thread end. [AThread] Thread end. main end!
join()方法注意事项: 1. 当一个线程s在另一个线程t上调用t.join() 此线程s将被挂起,直到目标线程t结束才恢复(此时t.isAlive()返回为假) 也可以在调用join()时带上一个超时参数(单位可以是毫秒,或者毫秒和纳秒) 当目标线程在这段时间内还没有结束的话,join()方法总能返回 对join()方法的调用可以被中断,做法是在调用线程上调用interrupt()方法。 2. 当线程生成后,但还未被起动,isAlive()将返回false,调用它的join()方法是没有作用的 将直接继续向下执行
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。