This week's book giveaway is in the Servlets forum.
We're giving away four copies of Murach's Java Servlets and JSP and have Joel Murach on-line!
See this thread for details.
The moose likes Java in General and the fly likes Java thread question... 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 » Java in General
Bookmark "Java thread question..." Watch "Java thread question..." New topic
Author

Java thread question...

Rahul Ba
Ranch Hand

Joined: Oct 01, 2008
Posts: 205


The output is:

Thread 1 :
Test Value : 10
Thread 2 :
Test Value : 10

but I was expecting output as:


Thread 1 :
Test Value : 10
Thread 2 :
Test Value : 0


why I am wrong?
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 18500
    
  40

Rahul Ba wrote:but I was expecting output as:

Thread 1 :
Test Value : 10
Thread 2 :
Test Value : 0


why I am wrong?



Care to tell us why you were expecting such a result?

Henry
Randall Twede
Ranch Hand

Joined: Oct 21, 2000
Posts: 4340
    
    2

the only way you could get the expected results is if you changed
testValue = 10;
to something like this
if(testValue == 0)
{
testValue = 10;
}
else
{
testValue = 0;
}


SCJP
Visit my download page
Rahul Ba
Ranch Hand

Joined: Oct 01, 2008
Posts: 205
I was thinking because, each thread keeps copy variable which is not shared to any other thread. i.e
When multiple threads using the same variable, each thread will have its own copy of the local cache for that variable. So, when it's updating the value, it is actually updated in the local cache not in the main variable memory.
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 18500
    
  40

Rahul Ba wrote:I was thinking because, each thread keeps copy variable which is not shared to any other thread. i.e
When multiple threads using the same variable, each thread will have its own copy of the local cache for that variable. So, when it's updating the value, it is actually updated in the local cache not in the main variable memory.


Each thread does have its own copy of the variable. And each copy of the variable is in main memory (different memory, of course).

And since each thread is setting its own copy of the varible to 10, before printing it, it is safe to assume that "10" is always printed.

Henry
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Java thread question...
 
Similar Threads
volatile example
volatile and static keywords
Thread and volatile
Volatile Keyworld
a tip on threads: (follow up)