Java 中线程的 join2025年3月28日 | 阅读 5 分钟 Java 中的 `join()` 方法由 `java.lang.Thread` 类提供,它允许一个线程等待直到另一个线程完成其执行。假设 `th` 是 `Thread` 类的一个对象,其线程正在执行,那么 `th.join();` 语句确保 `th` 在程序执行下一条语句之前完成。当有多个线程调用 `join()` 方法时,就会发生 `join()` 方法的重载,允许开发人员或程序员指定等待时间。然而,与 Java 中的 `sleep()` 方法类似,`join()` 方法也依赖于操作系统来计时,所以我们不应假定 `join()` 方法的等待时间与参数中指定的时间相等。以下是三个重载的 `join()` 方法。 重载 `join()` 方法的描述join(): 当调用 `join()` 方法时,当前线程停止执行,并进入等待状态。当前线程将一直处于等待状态,直到调用 `join()` 方法的线程达到其死亡状态。如果发生线程中断,则会抛出 `InterruptedException`。 语法 join(long mls): 当调用 `join()` 方法时,当前线程停止执行,并进入等待状态。当前线程将一直处于等待状态,直到调用 `join()` 方法的线程死亡,或者指定的等待时间(以毫秒为单位)结束。 语法 join(long mls, int nanos): 当调用 `join()` 方法时,当前线程停止执行,并进入等待状态。当前线程将一直处于等待状态,直到调用 `join()` 方法的线程死亡,或者指定的等待时间(以毫秒和纳秒为单位)结束。 语法 Java `join()` 方法的示例以下程序演示了 `join()` 方法的用法。 文件名: ThreadJoinExample.java 输出 The current thread name is: main The current thread name is: Thread - 0 0 The current thread name is: Thread - 0 1 The current thread name is: main The current thread name is: Thread - 1 0 The current thread name is: Thread - 1 1 The current thread name is: Thread - 2 0 The current thread name is: Thread - 2 1 解释: 上面的程序表明,第二个线程 `th2` 在第一个线程 `th1` 结束之后开始,而第三个线程 `th3` 在第二个线程 `th2` 结束或死亡之后开始工作。 `Join()` 方法:`InterruptedException`我们在 `join()` 方法的描述中了解到,每当发生线程中断时,都会导致 `InterruptedException` 的抛出。以下示例演示了这一点。 文件名: ThreadJoinExample1.java 输出 The exception has been caught. java.lang.InterruptedException `join()` 方法的更多示例让我们看一些其他的例子。 文件名: TestJoinMethod1.java 输出 1 2 3 4 5 1 1 2 2 3 3 4 4 5 5 在上面的示例中,我们可以看到,当 `t1` 完成其任务后,`t2` 和 `t3` 开始执行。 `join(long miliseconds)` 方法示例文件名: TestJoinMethod2.jav 输出 1 2 3 1 4 1 2 5 2 3 3 4 4 5 5 在上面的示例中,当 `t1` 完成其任务 1500 毫秒(3 次)后,`t2` 和 `t3` 开始执行。 下一主题Java-命名线程和当前线程 |
我们请求您订阅我们的新闻通讯以获取最新更新。