Java 并发性 – join() 方法
join 函数
此函数用于将一个线程的执行开始部分连接到另一个线程的执行末尾。这样,可以确保在第二个线程停止执行之前,第一个线程不会运行。此函数等待特定毫秒数,直到线程终止。
请看以下示例 −
示例
import java.lang.*; public class Demo implements Runnable{ public void run(){ Thread my_t = Thread.currentThread(); System.out.println("The name of the current thread is " + my_t.getName()); System.out.println("Is the current thread alive? " + my_t.isAlive()); } public static void main(String args[]) throws Exception{ Thread my_t = new Thread(new Demo()); System.out.println("The instance has been created and started"); my_t.start(); my_t.join(30); System.out.println("The threads will be joined after 30 milli seconds"); System.out.println("The name of the current thread is " + my_t.getName()); System.out.println("Is the current thread alive? " + my_t.isAlive()); } }
输出
The instance has been created and started The threads will be joined after 30 milli seconds The name of the current thread is Thread-0 The name of the current thread is Thread-0 Is the current thread alive? true Is the current thread alive? true
名为 Demo 的一个类实现了 Runnable 类。定义了一个“run”函数,将当前线程指定为新创建的 Thread。在主函数中,创建了该线程的一个新实例,并使用“start”函数开始该线程。该线程在特定时间后与另一个线程 join。屏幕上显示相关消息。
广告