Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Apply synchronized on Class non static attribute

public class MainClass {
public static void main(String[] args) {

    T1 ok = new T1();
    T2 ok1 = new T2();
    ok.start();
    ok1.start();
}

}

public class T1 extends Thread {

@Override
public void run() {
    DemoClass q = new DemoClass();
    for (int i = 0; i <= 5; i++)
        try {
            q.demoMethod();
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
}

}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

public class T2 extends Thread {

@Override
public void run() {
    DemoClass q = new DemoClass();
    for (int i = 0; i <= 5; i++)
        try {
            q.demoMethod1();
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
}

}

public class DemoClass {
String s = "";
String s1 = "";
public void demoMethod() throws InterruptedException {
    System.out.println(Thread.currentThread().getName() + " Entered m1");

    synchronized (s) {
        System.out.println(Thread.currentThread().getName() + " Inside m1 ");

        Thread.sleep(5000);
    }
    System.out.println(Thread.currentThread().getName()+" m1");

}

public void demoMethod1() throws InterruptedException {
    System.out.println(Thread.currentThread().getName() + " Entered m2");


        System.out.println(Thread.currentThread().getName() + " Inside m2 ");

        Thread.sleep(5000);
    
    System.out.println(Thread.currentThread().getName()+" m2");

}

}

Even when I created separate objects of DemoClass, then called separate methods through separate threads. why does only one thread work at one time?

Or if someone can suggest which type of locking will we call for the code in DemoClass

>Solution :

You’re synchronizing on s, which is always the same object.

Don’t do that. Synchronize on this if you’re going to synchronize on anything.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading