I'll give the answer a shot. For sync to work, the threads in question must be accessing the same object. So in the example where you create two different instances of MyClass, you have two seperate objects and sync will not happen. The example you give where you create one object and start two threads is the correct example. Of course, you must still have a syncronized block of code, but I assume you realize that.
That's a very concise example to get to this discussion. When you make two objects and put them on two threads, each instance only has to work on a single thread. That's the easy way to do things - a "non-threadsafe" approach.
When you run two threads with the same instance of your runnable the JVM is allowed to run one line of code for thread 1 and another line of code for thrad 2, and can even break up parts of lines. So if you do something as simple as:
you can be surprised to find that another thread changed memberVar to 437 in between those lines. If you know a class will be used this way, or you want to make it possible, you have to make it thread safe.
You have to think about any resources that might be shared by two threads in the same object instance. Member variables, any other external objects that both threads might reference, etc. It's likely you'll want to synchronize methods or code blocks (prefer code blocks) that access such shared resources.
If each thread needs its own variables or resources or whatever, make them as local variables. Each thread gets its own set of local variables on the stack.
Any of that make sense?
A good question is never answered. It is not a bolt to be tightened into place but a seed to be planted and to bear more seed toward the hope of greening the landscape of the idea. John Ciardi
Joined: Jun 10, 2003
Thanks Stan - that's what I thought. In Approach 1 where I have two objects how does the control flow? Let's say I have that code in the main method of a class called MainClass. After I do the t1.start(), does the main thread returns immdtly to the next line t2.start() without waiting for the t1's run method to finish? Assuming I have no code to share between them and I am taking approach 1, if main method doesn't wait on the t1's thread to finish and goes to the next line, it'll look like multi threading to me...
Joined: Jan 29, 2003
The main thread will start up T1 and then start up T2. You have no guarantees about whether T1 will actually execute any statements before T2 or not. If they both run a while and do some operations that yield the CPU, the JVM can interleave the execution ... a few instructions from T1, a few from T2, a few from T1 and so on. Meanwhile the main thread is free to go do other things and even exit. If you need to bring things together at the end, say to present the result of a parallel calculation, look into Thread.join().
subject: threading single instance vs multiple instances