posted 14 years ago
In your main() method, you create one ReadingFile object, and two different FileRead objects. If readFile() is a synchronized method defined in ReadingFile, then every time that method is called, it's synchronized on the same single instance of ReadingFile, and synchronization prevents two method calls from occurring concurrently on the same instance. That gives you the output you expect, apparently.
However if readFile() is a synchronized method defined in FileRead, then when that method is called using two different FileRead objects, synchronization has no effect. This is normal for synchronized instance methods - they only affect concurrent calls using the same instance. They have no effect on calls using different instances.
Note that if readFile() were a static synchronized method in ReadFile, then synchronization would prevent multiple concurrent invocations of the method, period. Static synchronized methods exclude execution of other static synchronized methods in the same class, regardless of what instances may have been involved. That's how they were designed. But if the method is not static, then synchronization is tied to the specific instances involved.
Note - I'm not suggesting you should rewrite readFile() to be static, as that's probably too much work for this example. I just offer this information for comparison. Synchronized instance methods and synchronized static methods behave differently, and that's a difference you need to pay attention to.