aspose file tools*
The moose likes Threads and Synchronization and the fly likes Threads and a local variable Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Java 8 in Action this week in the Java 8 forum!
JavaRanch » Java Forums » Java » Threads and Synchronization
Bookmark "Threads and a local variable" Watch "Threads and a local variable" New topic
Author

Threads and a local variable

Allen Bandela
Ranch Hand

Joined: Feb 16, 2006
Posts: 128

I'm not sure if this is even a sensible question.
I was wondering if the following code can ever print a 1.

And the output on several runs has always been:
0
0
0
0
0

My aim in this program is to let all the threads run line 1 and sleep. After that, I hoped to see a thread modify count and sleep. Now, the former scenario having occured, all the threads must print a value greater than 0.
Am I right in my thinking? This problem is not a real-world development problem, its just a thing that came into my mind.
[ November 17, 2006: Message edited by: Allen Sylvester ]
Purushoth Thambu
Ranch Hand

Joined: May 24, 2003
Posts: 425
Each thread has it's own local copy. Local objects are allocated in thread's stack not in heap. So any modification you make on local member of one thread will not be visible to other thread. You need common shared object if you want threads to interact.

What you are trying to accomplish is this

[ November 17, 2006: Message edited by: Purushothaman Thambu ]
Sam Codean
Ranch Hand

Joined: Feb 26, 2006
Posts: 194
try putting these instead and you will see what you want to



Your count was declared in the function stack which is not shared between instances you need to have it declared shared or static


-Sam Codean<br />SCJP 1.4 (98%)<br />SCJD 5.0 (87.5%)
Allen Bandela
Ranch Hand

Joined: Feb 16, 2006
Posts: 128

Thanks guys. I was'nt sure local variables were not shared by threads..was'nt even thinking in terms of different call stack for each thread... geez..thanks again.
 
jQuery in Action, 2nd edition
 
subject: Threads and a local variable
 
Similar Threads
Single thread that runs 5 times, sleeps, then runs 5 more times
Sharing of Memory in Threads?
Help with threads/printout.
Threads Behavior of run and Start methods.
Thread.sleep() not working as expected