Jaikant Bhagwan Das
Jaikant Bhagwan Das

Reputation: 227

Synchronization confusion in Java Thread Example

public class Mythread extends Thread{
    Parenthesis p = new Parenthesis();
    String s1;
    Mythread(String s){
        s1 = s;
    }
    public void run(){
        p.display(s1);
    }
    public static void main(String[] args) {
        Mythread t1 = new Mythread("Atul");
        Mythread t2 = new Mythread("Chauhan");
        Mythread t3 = new Mythread("Jaikant");
        t1.start();
        t2.start();
        t3.start();

    }

}

class Parenthesis{
    public void display(String str){
        synchronized (str) {
            System.out.print("("+str);  
            try {
                Thread.sleep(1000);
                //System.out.print("("+Thread.currentThread().getName());
            } catch (Exception e) {
                System.out.println(e);
            }
            System.out.print(")");
        }


}
}

I am getting output like (Atul(Chauhan(Jaikant))). As per my knowledge each Thread's object has own copy of Parenthesis's object that's why getting output like (Atul(Chauhan(Jaikant))).So even synchronizing the method display() will not produce the result like (Atul)(Chauhan)(Jaikant). So if I want desired output I have to make syncronized static display() method. Correct me if I am worng.

Upvotes: 0

Views: 96

Answers (1)

Klas Lindbäck
Klas Lindbäck

Reputation: 33273

If you want output like (Atul)(Chauhan)(Jaikant) you need all threads to synchronize on the same object.

Example:

class Parenthesis{
    static final String syncObject = "Whatever";

    public void display(String str){
        synchronized (syncObject) {
            System.out.print("("+str);  
            try {
                Thread.sleep(1000);
                //System.out.print("("+Thread.currentThread().getName());
            } catch (Exception e) {
                System.out.println(e);
            }
            System.out.print(")");
        }
    }
}

Upvotes: 2

Related Questions