Java Multithreading concept and join() method

后端 未结 12 1366
太阳男子
太阳男子 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:05

    I'm not able to understand the flow of execution of the program, And when ob1 is created then the constructor is called where t.start() is written but still run() method is not executed rather main() method continues execution. So why is this happening?

    This depends on Thread Scheduler as main shares the same priority order. Calling start() doesn't mean run() will be called immediately, it depends on thread scheduler when it chooses to run your thread.

    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??

    This is because of the Thread.sleep(1000) in your code. Remove that line and you will see ob1 finishes before ob2 which in turn finishes before ob3 (as expected with join()). Having said that it all depends on when ob1 ob2 and ob3 started. Calling sleep will pause thread execution for >= 1 second (in your code), giving scheduler a chance to call other threads waiting (same priority).

提交回复
热议问题