aspose file tools*
The moose likes Threads and Synchronization and the fly likes Main(Parent) and Child threads runs parallely? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Threads and Synchronization
Bookmark "Main(Parent) and Child threads runs parallely?" Watch "Main(Parent) and Child threads runs parallely?" New topic
Author

Main(Parent) and Child threads runs parallely?

Senthil Kumar Sekar
Ranch Hand

Joined: Aug 08, 2010
Posts: 45

Does Main thread runs parallely with the thread being created in the same thread?


Sometimes the output come as 4950 and sometime it comes as 0.

I heard that thread behavior cannot be judged.But this looks more weird - Both threads runs simultaneously and main thread gets completed before child thread?

I guess they are considered as 2 separate threads and not parent and child here.Is that so?

Alexei Kaigorodov
Greenhorn

Joined: Feb 24, 2008
Posts: 17
Senthil Kumar Sekar wrote:I heard that thread behavior cannot be judged.But this looks more weird - Both threads runs simultaneously and main thread gets completed before child thread?

This is not weird. This is expected behaviour.
Senthil Kumar Sekar wrote:I guess they are considered as 2 separate threads and not parent and child here.Is that so?

What do you mean by child and parent? Why do you think that child/parent relationship in Java is supported in any way?
Jeff Verdegan
Bartender

Joined: Jan 03, 2004
Posts: 6109
    
    6

Senthil Kumar Sekar wrote:Does Main thread runs parallely with the thread being created in the same thread?


Yes. That's the whole point of multithreading.

However, that doesn't mean that both threads will be executing simultaneously. Depending on the hardware, the OS, what else is running on the system, and the threads' mix of CPU and I/O, they may run simultaneously, or they may take turns, or one may run to completion before the other one even starts. We can't predict that and we can't control it.

In your case, the main thread could look at the "b" variable before the other thread starts, after it's done, or anywhere in between. Also, since b is not declared volatile and you don't use syncing, any value the the second thread writes to b might not be visible to the main thread right away--if it reads b, it may still see the previous value.
Jeff Verdegan
Bartender

Joined: Jan 03, 2004
Posts: 6109
    
    6

Senthil Kumar Sekar wrote:
I guess they are considered as 2 separate threads and not parent and child here.Is that so?


Yes, they are two completely independent threads. The fact that one is the "parent" of the other has no effect on their scheduling.
 
Don't get me started about those stupid light bulbs.
 
subject: Main(Parent) and Child threads runs parallely?