006 join method in thread

I. Overview

The core function of the join method is:

  The current thread waits for the child thread to end.

We can see that the overloading of the method is actually how long the calling thread waits for the child thread.

If no parameters are passed, the default is to run after the child thread is completed.


 

2. Test case

public  class JoinClass {
    
    public  static  void main(String[] args) {
         // Create a thread and print 1 to 1000. 
        Thread thread = new Thread() {
            @Override
            public void run() {
                print();
            }
        };
        // Start the thread 
        thread.start(); 
      // Join the child thread join, then the main thread will wait for the child thread to complete the task.
      thread.join();
// The main thread also does the same print(); } public static void print() { for(int i = 0 ; i<1000;i++) System.out.println(Thread.currentThread().getName() + " running .... i="+i); } }

Now we create a task that prints 1 to 1000, the main thread and a child thread separately.

The effect of printing is that the main thread and the child thread constantly switch the running state.

When we add a line to the original code.

Looking at the red part, the main thread will wait for the child thread to complete the task before executing the print() method.


 

3. Analysis

  Once the code in the red part is added, the main thread will block itself and will not wake up until the child thread completes its task.

    Therefore, the thread.join() method must be before the print() method, otherwise it will not start blocking when the main thread starts the task.

 [understand]:

  We can think of the join() method as a method that blocks the current thread itself until the waiting thread finishes.


 4. The never-ending cycle 

public class ForeverThread {
    
    public  static  void main(String[] args) throws Exception {
         // The main thread waits for it to finish before starting its own task... 
        Thread.currentThread().join();
    }
}

In the above code, the main thread has been waiting for the main thread to finish running by itself.

  The main thread has been waiting for it to finish running.

  Then there will be a cycle.

        wait

    main thread --- ------> main thread

        wait

As above, the main thread can lock itself and never ends.


V. An example 

  

public class TaskThread {
    public static void main(String[] args) throws Exception {
        long startTime = System.currentTimeMillis();
        Thread t1 = new Thread(new Task("task1",1));
        Thread t2 = new Thread(new Task("task2",2));
        Thread t3 = new Thread(new Task("task3",3));
        t1.start();
        t2.start();
        t3.start();
        t1.join();
        t2.join();
        t3.join();
        long endTime = System.currentTimeMillis();
        System.out.println("main thread is done,spned time is = " + (endTime - startTime));
    }
    
}

class Task implements Runnable{
     // The name of the task 
    private final String taskName;
     // The time spent by the task 
    private final long costTime;
     public Task(String taskName , long costTime) {
         this .taskName = taskName ; 
         this .costTime = costTime;
    }
    
    public void run() {
        try {
            TimeUnit.SECONDS.sleep(costTime);
            System.out .println ( " Task name = " + taskName + " Completed... " );
        } catch (InterruptedException e) {
            e.printStackTrace ();
        }
    }
    
}

We created a thread task class, which needs to pass in the name of a task and the time a thread needs to spend.

In the main thread, we created three threads, started them separately, and used join. Now the result of running is: 

Task name = task1 completed...
Task name = task2 completed...
Task name = task3 completed...
main thread is done,spned time is = 3002

  This is easy to understand: the main thread will terminate itself after the thread that took the longest time finishes.

Let's adjust the order in which the code runs:

  

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

Now 1 thread runs first, then the main thread waits for 1 thread to end, then starts 2 threads, and so on.

  Then, this method is actually equivalent to a serialized operation mode, that is, queuing.

Via this example:

  We know that join is blocking itself, waiting for the end of the blocking task before running itself.

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325113188&siteId=291194637