Reputation: 147
Here we have 2 thread class objects t1 and t2.
main()
{
//object creation
t1.start();
t2.start();
}
this logically means that first line 1 will execute and finish and hence the thread and then the line 2 will execute. Then could anyone explain how java creates two different threads and at the same time.
Upvotes: 0
Views: 51
Reputation: 4065
t1.start()
will launch a new thread that will be executed in parallel (not blocking main) so t2.start()
will launch another thread in parallel either t1's thread has finished or not.
This way at the end you'll have three threads running in parallel (t1, t2 and the main thread).
Upvotes: 0
Reputation: 1097
that first line 1 will execute and finish...: This is true.
... and hence the thread: Not true
Your conclusion is incorrect. The call t1.start()
is just a normal function call with respect to the current thread executing main. t1.start()
will be executed and hence the current thread will wait for the call to finish.
But, t1.start();
creates a new Thread and returns. Now this thread is independent of the current thread executing main, and can execute at any time in the future. Also, the current thread doesn't wait for the created thread to finish executing. This explains why your conclusion is false.
Upvotes: 4