• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

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

 
Rachel Glenn
Ranch Hand
Posts: 95
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
(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
Posts: 157
1
Android Java MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 9528
33
Android Google Web Toolkit Hibernate IntelliJ IDE Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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...
 
Rachel Glenn
Ranch Hand
Posts: 95
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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?
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic