Home > front end >  Why does adding a synchronized block around this code change program ouput?
Why does adding a synchronized block around this code change program ouput?

Time:01-28

class Demo extends Thread{
    Test x;
    String name;
    String task;

    public Demo(String name, String task, Test p){
        this.name = name;
        this.task = task;
        x = p;
    }

    public void run(){
        synchronized (x) {
            x.message(name, task); 
        } 
    }



    public static void main(String[] args) {
        Test t = new Test();

        Demo d = new Demo("Jack", "Cutting",t);
        Demo d1 = new Demo("Jacoe", "Cooking",t);
        Demo d2 = new Demo("Bob", "Cleaning",t);
        d.start();
        d1.start();
        d2.start();

    }
    
}

class Test{
    void message(String name, String task){

        System.out.println(name);
        try{
            Thread.sleep(5000);
        }catch(Exception e){

        }
        System.out.println(task);

    }

}

This is a simple program I created to practice multithreading and synchronization in java. I was wondering if somebody can explain to me why the output is different when the synchronized block is removed from the public void run() method?

With: With synchronized block

Without: Without synchronized block

CodePudding user response:

The program starts threads. The OS has to schedule when they run, which can seem arbitrary. Then without locking the threads may interleave their actions.

In the synchronized case, all the threads' run methods are synchronizing on the same object, so only one of them can execute at a time. There is no guarantee which of them comes first, the scheduler can pick whichever it wants. In your case it picked the third thread before the second one.

The individual output lines don't get interleaved in any case because the printstream is synchronized.

CodePudding user response:

The output was never deterministically ordered or guaranteed to be the same order. It was always "undefined; the system can do it in whatever order it ends up doing."

CodePudding user response:

synchronized is like the lock statement in c#

Only one thread can enter the synchronized block at the same time.
The other threads have to wait in front of the synchronized block.

Total runtime with synchronized should be 15 sec.
Total runtime without should be 5 sec, because all 3 Threads run at the same time.

  •  Tags:  
  • Related