温馨提示×

如何使用Java中的join方法

小樊
82
2024-09-13 00:30:17
栏目: 编程语言

在Java中,join()方法是Thread类的一个方法,它用于等待一个线程完成(终止)后,才继续执行当前线程

以下是如何使用join()方法的示例:

public class JoinExample {
    public static void main(String[] args) throws InterruptedException {
        // 创建并启动一个新线程
        Thread newThread = new Thread(() -> {
            for (int i = 0; i < 5; i++) {
                System.out.println("New thread: " + i);
                try {
                    Thread.sleep(1000); // 模拟耗时操作
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        newThread.start();

        // 在主线程中调用join()方法,等待新线程完成后再继续执行
        newThread.join();

        // 输出主线程的内容
        System.out.println("Main thread continues after the new thread has finished.");
    }
}

在这个示例中,我们创建了一个新线程newThread,该线程会打印0到4的数字,每隔1秒打印一次。然后在主线程中调用newThread.join(),使得主线程等待新线程完成后再继续执行。因此,输出结果将首先显示新线程的内容,然后才显示主线程的内容。

注意:join()方法可能会抛出InterruptedException异常,因此需要使用try-catch语句进行处理。

0