• Post Reply Bookmark Topic Watch Topic
  • New Topic

threads and access to variables

 
Vernon Gibson
Ranch Hand
Posts: 35
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Let's assume that Class1 has the following declaration
>public String foo = new String();
...And that Class1 starts Class2 as a new Thread
>Class2 c2 = new Class2;
>Class2.start();
...Does Class2 have access to foo declared in Class1??
Class1.foo = "bar";
Thanks,
Vernon
 
Peter den Haan
author
Ranch Hand
Posts: 3252
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Vernon Gibson:
Let's assume that Class1 has the following declaration
>public String foo = new String();
...And that Class1 starts Class2 as a new Thread
>Class2 c2 = new Class2;
>Class2.start();
...Does Class2 have access to foo declared in Class1??
Class1.foo = "bar";

Yes, but not with this syntax (unless foo is static, that is). There is no isolation between threads in their access to each other's objects. In fact, a thread does not "own" any objects.
Actually, that's not entirely true -- but that is in most cases an academic point. On multiprocessor systems, you don't have any guarantee whatsoever that thread A can see modifications made by thread B until both have synchronized on the same object. But that is what you should do when threads share their data anyway.
- Peter
 
Vernon Gibson
Ranch Hand
Posts: 35
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for clearing that up Peter.
I'm going to implement this in a situation where the creating class will hold statistics that will be updated by each thread as it is created and destroyed (i.e. how many active threads).
Thanks again
Vernon
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!