gudii9
asked on
thread synchronization
Hi,
I am working on below example
http://www.avajava.com/tutorials/lessons/how-do-i-use-a-synchronized-block-in-a-static-method.html
I have not understood what author is trying to demonstrate as below
I got below output which is not clear to me
hello
goodbye
please advise
Any links resources ideas highly appreciated. Thanks in advance
I am working on below example
http://www.avajava.com/tutorials/lessons/how-do-i-use-a-synchronized-block-in-a-static-method.html
I have not understood what author is trying to demonstrate as below
It's possible to synchronize a static method. When this occurs, a lock is obtained for the class itself. This is demonstrated by the static hello() method in the SyncExample class below. When we create a synchronized block in a static method, we need to synchronize on an object, so what object should we synchronize on? We can synchronize on the Class object that represents the class that is being synchronized. This is demonstrated in the static goodbye() method of SyncExample. We synchronize on SyncExample.class.
I got below output which is not clear to me
hello
goodbye
please advise
Any links resources ideas highly appreciated. Thanks in advance
ASKER
you would get the same output even if you remove the synchronize modifer/block.
you mean below synchronized block inside goodbye() method right?
public static void goodbye() {
synchronized (SyncExample.class) {
System.out.println("goodby
}
When you say removing synchronize modifer/block means as below right comment those two lines?
public class SyncExample {
public static void main(String[] args) {
hello();
goodbye();
}
public static synchronized void hello() {
System.out.println("hello");
}
public static void goodbye() {
//synchronized (SyncExample.class) {
System.out.println("goodbye");
// }
}
}
Can you please point me to better practical example on this concept to understand clearly.Please advise
ASKER
Please advise
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
I'll try and get back to you soon with one.
Sure.
ASKER
using the synchronized block (like in goodbye() method) with this class as the argument, ie. SyncExample.class
Can there be synchronized blocks without any argument(like class name)?
Is that is possible?
The main point that it is trying to convey is that the two methods have the same functionality. Putting the synchronized keyword in the method declaration (like in hello() method) is essentially the same as using the synchronized block (like in goodbye() method) with this class as the argument, ie. SyncExample.class