以下是一个使用 join 方法的 Java 多线程代码示例:

public class JoinThreadExample {

    public static void main(String[] args) throws InterruptedException {
        Thread t1 = new Thread(() -> {
            System.out.println('Thread 1 started');
            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println('Thread 1 finished');
        });

        Thread t2 = new Thread(() -> {
            System.out.println('Thread 2 started');
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println('Thread 2 finished');
        });

        t1.start();
        t2.start();

        // 使用 join 方法,让主线程等待 t1 和 t2 线程执行完毕后再继续执行
        t1.join();
        t2.join();

        System.out.println('All threads finished');
    }
}

在这个例子中,我们创建了两个线程 t1 和 t2,它们分别会休眠5秒和3秒,然后打印出一条信息。我们使用 join 方法将主线程阻塞,直到 t1 和 t2 线程执行完毕后再继续执行主线程。最后,我们打印出一条 'All threads finished' 消息,表示所有线程都已经执行完毕。

Java 多线程中 join 方法的应用示例

原文地址: https://www.cveoy.top/t/topic/ogjR 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录