Java Multithreading concept and join() method

后端 未结 12 1390
太阳男子
太阳男子 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条回答
  •  萌比男神i
    2020-11-28 02:19

    when ob1 is created then the constructor is called where "t.start()" is written but still run() method is not executed rather main() method is executed further. So why is this happening?

    here your threads and main thread has equal priority.Execution of equal priority thread totally depends on the Thread schedular.You can't expect which to execute first.

    join() method is used to wait until the thread on which it is called does not terminates, but here in output we see alternate outputs of the thread why??

    Here your calling below statements from main thread.

         ob1.t.join();
         ob2.t.join();
         ob3.t.join();
    

    So main thread waits for ob1.t,ob2.t,ob3.t threads to die(look into Thread#join doc).So all three threads executes successfully and main thread completes after that

提交回复
热议问题