File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Threads and Synchronization and the fly likes Threads and Synchronization Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login


Win a copy of The Mikado Method this week in the Agile and other Processes forum!
JavaRanch » Java Forums » Java » Threads and Synchronization
Reply Bookmark "Threads and Synchronization" Watch "Threads and Synchronization" New topic
Author

Threads and Synchronization

alzamabar
Ranch Hand

Joined: Jul 24, 2002
Posts: 379
Hi, let's suppose that i have the following methods:
synchronized public Object obj1() {
return new Object();
}
synchronized public Object obj2() {
return new Object();
}
Forgot the logic of it, as it is not the focus of the post , but suppose to have two threads belonging to two different istances:
if thread1 calls obj1, can thread2 call obj2? From what i learned on a book, even if the two threads call different methods, thread2 cannot call any other synchronized method until thread1 has finished with its call.
Regards,
Marco


Marco Tedone<br />SCJP1.4,SCJP5,SCBCD,SCWCD
John Smith
Ranch Hand

Joined: Oct 08, 2001
Posts: 2937

if thread1 calls obj1, can thread2 call obj2?

The answer to this question depends on which object(s) is/are used to call methods obj1() and obj2() from threads thread1 and thread2. If it is the same object, then the methods will be run in sequence. If it is two different objects (two instances of a class that has synchronized methods), one of them can run method obj1() while the other one can run method obj2().
Perhaps this will be clear if you run the following code:

Output:
in method obj1(), sleeping
in method obj2(), sleeping
woke up, still in method obj1()
woke up, still in method obj2()
As you can see from the output, while thread1 runs method obj1(), nothing prevents thread2 from running method obj2().
However, replace the code...
Client thread1 = new Client(new FalseSafety());
Client thread2 = new Client(new FalseSafety());
with...
FalseSafety falseSafety = new FalseSafety();
Client thread1 = new Client(falseSafety);
Client thread2 = new Client(falseSafety);
... and now the methods ob1() and obj2() will be run in sequence.
The key thing to understand is that is not really a method that can be synchronized, but the object that is used to call the synchronized method. In fact,

is equivalent to

Hope this is clear,
Eugene.
[ February 15, 2003: Message edited by: Eugene Kononov ]
alzamabar
Ranch Hand

Joined: Jul 24, 2002
Posts: 379
Thank you Eugene, it's clear.
Marco
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Threads and Synchronization
 
Similar Threads
Thread synchronization
Help Understand this Thread code
Reg. Some Thread basics
thread question
Thread synchronize question from JQ+ test