温馨提示×

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

小樊
83
2024-09-30 01:47:16
栏目: 编程语言
Java开发者专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

在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()方法等待新线程完成。当新线程执行完毕后,主线程会继续执行。

亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

0