Java 中 Thread 类的 join() 方法
javaobject oriented programmingprogramming更新于 2025/7/6 16:44:17
join 函数 −
join 方法确保当前线程等待,直到它应该连接的线程终止。此函数等待,直到调用该函数的线程终止。
语法
final void join() throws InterruptedException
让我们看一个例子 −
示例
public class Demo extends Thread{
public void run(){
System.out.println("sample ");
try{
Thread.sleep(10);
}
catch (InterruptedException ie){
}
System.out.println("only ");
}
public static void main(String[] args){
Demo my_obj_1 = new Demo();
Demo my_obj_2 = new Demo();
my_obj_1.start();
System.out.println("The first object has been created and started");
try{
System.out.println("In the try block, the first object has been called with the join function");
my_obj_1.join();
}
catch (InterruptedException ie){
}
System.out.println("The second object has been started");
my_obj_2.start();
}
}
输出
The first object has been created and started In the try block, the first object has been called with the join function sample only The second object has been started sample only
名为 Demo 的类扩展了 Thread 类。这里定义了一个 ‘run’ 函数,其中定义了一个 try catch 块。这里,在 try 块中,调用 sleep 函数,而 catch 块留空。在主函数中,创建了 Demo 对象的两个实例。声明第一个对象并使用 ‘join’ 函数调用它。对第二个对象也执行相同的操作,并显示相关消息。
相关文章
有用资源
java 参考教程 - 该教程包含有关 java 的更多信息:https://www.cainiaomax.com/java/

