温馨提示×

如何在java中使用join()等待线程完成

小樊
81
2024-09-30 01:47:16
栏目: 编程语言

在Java中,可以使用Thread.join()方法来等待一个线程完成

public class JoinExample {
    public static void main(String[] args) {
        // 创建一个新线程
        Thread newThread = new Thread(() -> {
            System.out.println("新线程开始执行...");
            try {
                // 模拟耗时任务
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("新线程执行完毕");
        });

        // 启动新线程
        newThread.start();

        try {
            // 使用join()方法等待新线程完成
            newThread.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println("主线程继续执行...");
    }
}

在这个例子中,我们创建了一个新线程,并在主线程中使用newThread.join()方法等待新线程完成。当新线程执行完毕后,主线程会继续执行。

0