java join方法
时间: 2024-06-10 19:01:35 浏览: 97
Java中的join()方法用于等待一个线程的结束。当在一个线程中调用另一个线程的join()方法时,当前线程将被阻塞,直到被调用的线程执行完毕。join()方法的语法如下:
```java
public final void join() throws InterruptedException
```
其中,join()方法没有返回值,但可能会抛出InterruptedException异常。
下面是一个简单的示例,演示了join()方法的使用:
```java
public class JoinExample {
public static void main(String[] args) throws InterruptedException {
Thread thread1 = new Thread(new MyRunnable(), "Thread 1");
Thread thread2 = new Thread(new MyRunnable(), "Thread 2");
thread1.start();
thread2.start();
thread1.join();
thread2.join();
System.out.println("All threads have finished execution.");
}
}
class MyRunnable implements Runnable {
@Override
public void run() {
System.out.println(Thread.currentThread().getName() + " is running."); try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + " has finished execution.");
}
}
```
在上面的示例中,我们创建了两个线程thread1和thread2,并启动它们。然后,我们使用join()方法等待这两个线程执行完毕。最后,当这两个线程都执行完毕后,输出"All threads have finished execution."。
阅读全文