views:

63

answers:

3

I am just playing around with threads in java. I have a class which implements runnable.

public class MyThread implements Runnable{

   private boolean finished;
   //Other variables

   public void run(){
      //Thread code
   }
}

My understanding is that each thread of type MyThread will have its own copy of member variables and writes to those member variables need not be synchronized. Is this assumption correct? If correct, access to what needs to be synchronized? Can someone care to give a outline or pseudo code.? Thanks.

A: 
  • Each MyThread instance is a new instance, just like normal classes and objects.
  • Variables of native types are copied. This means that changing the variable in one thread does nothing to the other thread. These do not have to be synchronized.
  • For objects their references are copied. This means that two threads may have a reference to the same object. If the two threads manipulate that object at the same time, this can go bad. Therefore, these accesses have to be synchronized.
Sjoerd
+6  A: 

Not necessarily. You could create multiple threads using the same instance of MyThread. For example:

MyThread x = new MyThread();
new Thread(x).start();
new Thread(x).start();
new Thread(x).start();

Now there will be three threads all running code in the same object.

I suggest you rename MyThread as it's not a thread - it's a task for a thread to perform. That makes it clearer (IMO).

Jon Skeet
@Jon - in this case, do all three Threads (running x) see *the same* finished field, so if `finished` is changed in one Thread, do the other two Threads see the change? Or is this an example where the `volatile` keyword would change behaviour?
Andreas_D
@Andreas_D: They would all be using the same field, but without the volatile modifier they may not see each other's changes.
Jon Skeet
Accepted. But does it mean that if threads operate on different instances,nothing has to be synchronized? Or what exactly is shared between threads operating on different instances of same type?
Yes, if they're running on different instances and using entirely distinct values (e.g. no references to shared other objects) it should be fine.
Jon Skeet
A: 

The Really Big Index trail on concurrency is well worth a read (yes, it has examples).

Catchwa