join() method in Thread

The join() method in Thread is used to let the calling Thread wait for the current Thread to finish executing before executing

Test code:

Scenario 1: do not call join()

public static void main(String[] args) throws InterruptedException {

        Thread t1 = new Thread(){
            @Override
            public void run() {
                for(int i = 1 ; i <= 100 ; i++){
                    System.out.println(Thread.currentThread().getName()+"-->"+i);
                }
            }
        };

        Thread t2 = new Thread(){
            @Override
            public void run() {
                for(int i = 1 ; i <= 100 ; i++){
                    System.out.println(Thread.currentThread().getName()+"-->"+i);
                }
            }
        };

        Thread t3 = new Thread(){
            @Override
            public void run() {
                for(int i = 1 ; i <= 100 ; i++){
                    System.out.println(Thread.currentThread().getName()+"-->"+i);
                }
            }
        };

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


        //Output the name of main thread
        System.out.println(Thread.currentThread().getName());
    }

Test result: first, the name of main thread is output, then t1, t2 and t3 are output successively.

Scenario 2: calling join() to make main thread wait

public static void main(String[] args) throws InterruptedException {

        Thread t1 = new Thread(){
            @Override
            public void run() {
                for(int i = 1 ; i <= 100 ; i++){
                    System.out.println(Thread.currentThread().getName()+"-->"+i);
                }
            }
        };

        Thread t2 = new Thread(){
            @Override
            public void run() {
                for(int i = 1 ; i <= 100 ; i++){
                    System.out.println(Thread.currentThread().getName()+"-->"+i);
                }
            }
        };

        Thread t3 = new Thread(){
            @Override
            public void run() {
                for(int i = 1 ; i <= 100 ; i++){
                    System.out.println(Thread.currentThread().getName()+"-->"+i);
                }
            }
        };

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

        t1.join();
        t2.join();
        t3.join();

        //Output the name of main thread
        System.out.println(Thread.currentThread().getName());
    }

When join() is called for t1, t2 and t3, t1, t2 and t3 will execute concurrently, but the main thread will always be in a blocking state and wait for t1, t2 and t3 threads to finish executing before executing.

Posted by ognotongo on Sun, 24 Nov 2019 11:52:31 -0800