1

定义

等待该线程终止,比如A线程调用了B线程的join,那么A线程要等到B线程执行完后,才可以继续执行。

示例

public class JoinDemo {
    static class JoinThread1 implements Runnable {
        Thread thread;

        public JoinThread1(Thread thread) {
            this.thread = thread;
        }

        @Override
        public void run() {
            System.out.println("thread1 start");
            try {
                thread.join();
                System.out.println("thread1 end");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    static class JoinThread2 implements Runnable {
        @Override
        public void run() {
            System.out.println("thread2 start");
            try {
                Thread.sleep(10000);
                System.out.println("thread2 end");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        JoinThread2 joinThread2 = new JoinThread2();
        Thread thread2 = new Thread(joinThread2);
        JoinThread1 joinThread1 = new JoinThread1(thread2);
        Thread thread1 = new Thread(joinThread1);

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

运行结果如下:
clipboard.png
线程1执行的时候,调用线程2的join,线程1不休眠,线程2休眠了10秒,从结果看出来,线程2执行完后,线程1才执行完。


大军
847 声望183 粉丝

学而不思则罔,思而不学则殆