Java Thread join() Method Explained

In Java, the join() method is used to wait for a thread to complete. When the join() method is called on an instance of a thread, the current thread will be blocked until the thread finishes execution or times out. It can be used to wait for other threads to complete before proceeding with the next operation. For example:

Thread thread1 = new Thread(() -> {
    // 一些耗时的操作
});

Thread thread2 = new Thread(() -> {
    // 一些耗时的操作
});

thread1.start();
thread2.start();

try {
    thread1.join(); // 等待thread1执行完成
    thread2.join(); // 等待thread2执行完成
} catch (InterruptedException e) {
    e.printStackTrace();
}

// 在这里可以执行接下来的操作

In the example above, by using the join() method to wait for the completion of thread1 and thread2 before proceeding with the next operations. If join() method is not called, threads will execute concurrently and the execution order cannot be guaranteed.

bannerAds