Java Multithreading concept and join() method

后端 未结 12 1369
太阳男子
太阳男子 2020-11-28 01:39

I\'m confused in join() method used in Threads in Java. In the following code:

// Using join() to wait for threads to finish.
class NewThread im         


        
12条回答
  •  南方客
    南方客 (楼主)
    2020-11-28 02:23

    You must understand , threads scheduling is controlled by thread scheduler.So, you cannot guarantee the order of execution of threads under normal circumstances.

    However, you can use join() to wait for a thread to complete its work.

    For example, in your case

    ob1.t.join();
    

    This statement will not return until thread t has finished running.

    Try this,

    class Demo {
       Thread t = new Thread(
                     new Runnable() {
                         public void run () {
                             //do something
                         }
                      }
        );
        Thread t1 = new Thread(
                     new Runnable() {
                         public void run () {
                             //do something
                         }
                      }
        );
        t.start(); // Line 15
        t.join();  // Line 16
        t1.start();
    }
    

    In the above example, your main thread is executing. When it encounters line 15, thread t is available at thread scheduler. As soon as main thread comes to line 16, it will wait for thread t to finish.

    NOTE that t.join did not do anything to thread t or to thread t1. It only affected the thread that called it (i.e., the main() thread).

    Edited:

    t.join(); needs to be inside the try block because it throws the InterruptedException exception, otherwise you will get an error at compile time. So, it should be:

    try{
        t.join();
    }catch(InterruptedException e){
        // ...
    }
    

提交回复
热议问题