wood burning stoves 2.0*
The moose likes Threads and Synchronization and the fly likes Why Both Threads Printing their own variable x value. Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Java » Threads and Synchronization
Bookmark "Why Both Threads Printing their own variable x value." Watch "Why Both Threads Printing their own variable x value." New topic
Author

Why Both Threads Printing their own variable x value.

Punya Pratap Singh
Ranch Hand

Joined: Nov 23, 2010
Posts: 80


In this Example when both threads are running they are printing their own values of variable x,I consider that if variable x is a global varibale for the class, then if one thread makes from x=7 to x= 8 then second thread should consider x=8,but it is considering it x=7 why ?

Please Expalin.

[NK: Added code tags. Please UseCodeTags while posting code]
Christophe Verré
Sheriff

Joined: Nov 24, 2005
Posts: 14688
    
  16

new T() means a new instance of T. So you have two new instances of T, each with its own instance variable. x is an instance variable of T. It's not static. Another instance of the same class won't interfere with it.


[My Blog]
All roads lead to JavaRanch
Punya Pratap Singh
Ranch Hand

Joined: Nov 23, 2010
Posts: 80
Thanks Christope Understood.

Then how can we create Dirty Data read problem in this Example.
Means if one thread makes x= 8 then next one should read it like x= 8 not 7.
please show me the way in the same example.

Thanks.
Christophe Verré
Sheriff

Joined: Nov 24, 2005
Posts: 14688
    
  16

By using the same instance ?
 
Don't get me started about those stupid light bulbs.
 
subject: Why Both Threads Printing their own variable x value.