*
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 Murach's Java Servlets and JSP this week in the Servlets 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: 14687
    
  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: 14687
    
  16

By using the same instance ?
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Why Both Threads Printing their own variable x value.
 
Similar Threads
difference betwen parameters and attributes
When the scheduler can get a thread back to runnable state?
A thread of doubt
doubt in threads