温馨提示×

Java中join方法的返回值是什么

小樊
82
2024-09-13 00:32:12
栏目: 编程语言

在Java中,join() 方法是 Thread 类的一个方法,用于等待线程执行完成。当你调用一个线程的 join() 方法时,当前线程会被阻塞,直到被调用的线程执行完成。join() 方法没有返回值,它的返回类型是 void

示例:

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

        Thread thread2 = new Thread(() -> {
            System.out.println("Thread 2 started");
            try {
                thread1.join(); // 等待thread1执行完成
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("Thread 2 finished");
        });

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

在这个示例中,thread2 会等待 thread1 执行完成后再继续执行。注意,join() 方法没有返回值。

0