File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes ch.9, problem 11   sierra/bates book - threads Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "ch.9, problem 11   sierra/bates book - threads" Watch "ch.9, problem 11   sierra/bates book - threads" New topic
Author

ch.9, problem 11 sierra/bates book - threads

Rachel Glenn
Ranch Hand

Joined: Oct 24, 2012
Posts: 95
(Below is the code for the problem from the book)

So I have 2 threads that are started, and both thread share the same run() function. It seems that, based on the answers, both threads share the instances of x and y declared in main. Why is that? Also, why declare x and y as final?







harshvardhan ojha
Ranch Hand

Joined: Jul 26, 2007
Posts: 157
    
    1

Rachel, this is the property of inner classes - you cannot access non-final variable inside an inner class defined in a different method.
Ankit Garg
Sheriff

Joined: Aug 03, 2008
Posts: 9321
    
  17

Rachel Glenn wrote:It seems that, based on the answers, both threads share the instances of x and y declared in main. Why is that?

How many objects/instances of ThreadDemo were created in the main method? There were only two instances created so both the threads have to share them they don't have any other choice. If you were creating ThreadDemo objects in the main method then both threads would have got separate copies of the objects...


SCJP 6 | SCWCD 5 | Javaranch SCJP FAQ | SCWCD Links
Rachel Glenn
Ranch Hand

Joined: Oct 24, 2012
Posts: 95
Ankit Garg wrote:
Rachel Glenn wrote:It seems that, based on the answers, both threads share the instances of x and y declared in main. Why is that?

How many objects/instances of ThreadDemo were created in the main method? There were only two instances created so both the threads have to share them they don't have any other choice. If you were creating ThreadDemo objects in the main method then both threads would have got separate copies of the objects...


I am a little confused by your response. The main method created 2 Threads. The main method also created the x and y objects. Why do the threads share a copy of x and y?
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: ch.9, problem 11 sierra/bates book - threads