I'm trying to explore static synchronized method I got the theoretical concept that it's acquire lock on class, not on instance. But I'm failed to create an example where I Can test it.
Here I have created the Code to test, But both instance are accessing static synchronized method at the same time.
class Demo{ public static synchronized void a(){ System.out.println("A Method " + Thread.currentThread().getName()); } } public class StaticSyn{ public static void main(String[] args){ Demo obj = new Demo(); Demo obj2 = new Demo(); Thread one = new Thread(){ @Override public void run(){ int i=0; while(i<5){ obj.a(); try{ Thread.sleep(100); }catch(InterruptedException e){ } i++; } } }; Thread two = new Thread(new Runnable(){ @Override public void run(){ int i=0; while(i<5){ obj2.a(); try{ Thread.sleep(100); }catch(InterruptedException e){ } i++; } } }); one.start(); two.start(); } } With static synchronized I'm getting this output.
A Method Thread-0 A Method Thread-1 A Method Thread-1 A Method Thread-0 A Method Thread-1 A Method Thread-0 A Method Thread-0 A Method Thread-1 A Method Thread-1 A Method Thread-0 Without static keyword I'm getting this output.
A Method Thread-0 A Method Thread-1 A Method Thread-1 A Method Thread-0 A Method Thread-0 A Method Thread-1 A Method Thread-0 A Method Thread-1 A Method Thread-1 A Method Thread-0 So, where is the problem? and How I can test that Just one object is accessing static synchronized method.
static synchronizedmethod inDemois equivalent to wrapping the method body insynchronized (Demo.class) { ... }.a()while the other is.System.outis internally synchronized already, there will be no difference whetherDemo.a()is synchronized or not.