• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Java thread question...

 
Rahul Ba
Ranch Hand
Posts: 206
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


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
Marshal
Pie
Posts: 21423
84
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 4469
3
Java Python Scala
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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;
}
 
Rahul Ba
Ranch Hand
Posts: 206
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Marshal
Pie
Posts: 21423
84
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic