Disclaimer: This code is copied from synchronized blocks for static and non-static methods
I made some modification to it. I want to know how to make threads call both synchronized static and non-static methods. I can make it work by wrapping the non-static method in a synchronized block. Is there any other way?
public class StaticNonStaticSynch { public static void main(String[] args) { final StaticNonStaticTest staticNonStaticTest = new StaticNonStaticTest(); Runnable runnable1 = new Runnable() { @Override public void run() { staticNonStaticTest.nonStaticMethod(); } }; Runnable runnable2 = new Runnable() { @Override public void run() { StaticNonStaticTest.staticMethod(); } }; Thread thread1 = new Thread(runnable1, "First Thread"); Thread thread2 = new Thread(runnable2, "Second Thread"); thread1.start(); thread2.start(); } } class StaticNonStaticTest { void nonStaticMethod() { //synchronized (StaticNonStaticTest.class){ for(int i=0;i<50;i++) { System.out.println("Non - Static method called by " + Thread.currentThread().getName() +" : = "+i); } // } } static synchronized void staticMethod() { for(int i=0;i<50;i++) { System.out.println("Static method called by " + Thread.currentThread().getName() +" : = "+i); } } }