在Java中,join()方法是Thread类的一个方法,用于等待线程的终止。当调用一个线程的join()方法时,当前线程会被阻塞,直到被调用的线程执行完毕。

join()方法有两个重载版本:

  1. void join():等待被调用线程执行完毕。
  2. void join(long millis):等待被调用线程执行完毕,最多等待指定的毫秒数。

如果被调用的线程已经终止,那么调用join()方法的线程会立即返回。

下面是一个示例代码,演示了join()方法的使用:

public class JoinExample {
    public static void main(String[] args) {
        Thread thread1 = new Thread(new MyRunnable(), "Thread 1");
        Thread thread2 = new Thread(new MyRunnable(), "Thread 2");

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

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

        System.out.println("All threads have finished execution.");
    }

    static class MyRunnable implements Runnable {
        @Override
        public void run() {
            System.out.println(Thread.currentThread().getName() + " started.");
            try {
                Thread.sleep(2000); // 模拟线程执行一段时间
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + " finished.");
        }
    }
}

在上面的示例中,主线程启动了两个子线程thread1和thread2,并调用它们的join()方法等待它们执行完毕。当两个子线程执行完毕后,主线程打印"All threads have finished execution."。注意,由于线程的执行是并发的,因此thread1和thread2的执行顺序是不确定的。但是,主线程会等待它们都执行完毕后再继续执行

java的join

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

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