If two threads are about to execute a synchronized method in a class, and both thread are using the same instance of the class to invoke the method, only one thread at a time will be able to execute the method.
For my code below, the main thread is doing fine, printing what I expected.
But when I started the other threads (A and B), their results are different.
I'm expecting that the output for A and B will be like this:
Instead of the same results as the main thread (nicely ordered 1-2-3 printouts), A and B printouts seem intertwined.
SCJP/OCPJP 6 | SCWCD/OCPJWCD 5 | OCMJEA in progress...
Joined: Jan 01, 2007
Even if I add a new class that implements Runnable and assigns it to the new thread, I'm still getting the same output.
I got the idea so I changed it into something like my 2nd post above. However, the printout is still the same. What I did was,
SyncClass - just ordinary class with the synchronized method. SyncJob - the Runnable class where SyncClass is instantiated and the synchronized method is called.
And then I realized that I'm still creating two different instances for the threads when the run is called. So I made the SyncClass the Runnable class instead, and removed the SyncJob totally.
The output is OK now. However this is not the design I want. I like to call a synchronized method from other classes that don't implement Runnable, and then see the actual synchronizing take effect. Any idea for this? [ August 12, 2008: Message edited by: Denise Saulon ]