• Post Reply Bookmark Topic Watch Topic
  • New Topic

UnAccepted Behavior of thread  RSS feed

 
gunjan bohra
Ranch Hand
Posts: 40
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I am executing following code in my programme
state=5;
for(; {
System.out.println(state);
Thread.sleep(1000);
}

While the above code was getting executed another thread Thread2 which has got access to the variable "state" changes the value of state to 10.
ow when the Thread1 returns for execution the code still prints out 5 instead of 10.
The thread still print 5 instead of 10 .
Why it's so ?
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24215
37
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Because each thread can have what amounts to a separate cache of main memory. Only synchronization can force a thread to reconcile its state with main memory. Therefore, if multiple threads access the same variable, the only proper way to do it is inside a synchronized method or block.
 
Henry Wong
author
Sheriff
Posts: 22866
119
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Ernest Friedman-Hill:
Therefore, if multiple threads access the same variable, the only proper way to do it is inside a synchronized method or block.


As an alternative -- if you are only doing single sets and gets -- is to simply declare the shared variable as volatile.

Henry
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24215
37
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Indeed.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!