On the execution order of threads plus synchronized keywords in java

< H2 > the first case < / H2 >
package com.btmans.thread;

public class TestSync implements Runnable{
    int b = 100;
    public synchronized void m1() throws Exception{
        b = 1000;
        Thread.sleep(5000);
        System.out.println("b="+b);
        
    }
    public synchronized void m2() throws Exception{
        Thread.sleep(3000);
        b = 2000;
    }
    @Override
    public void run() {
        // TODO Auto-generated method stub
        try {
            m1();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws Exception {
        
        TestSync ts = new TestSync();
        Thread t = new Thread(ts);
        t.start();
        ts.m2();
        System.out.println("=="+ts.b);
        
    }
}

the output result is
= = 1000
baked 1000

< H2 > the second case: add the following red code < / H2 >
package com.btmans.thread;

public class TestSync implements Runnable{
    int b = 100;
    public synchronized void m1() throws Exception{
        System.out.println("m1");""
        b = 1000;
        Thread.sleep(5000);
        System.out.println("b="+b);
        
    }
    public synchronized void m2() throws Exception{
        System.out.println("m2");""
        Thread.sleep(3000);
        b = 2000;
    }
    @Override
    public void run() {
        // TODO Auto-generated method stub
        try {
            m1();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    
    public static void main(String[] args) throws Exception {
        
        TestSync ts = new TestSync();
        Thread t = new Thread(ts);
        t.start();
        ts.m2();
        System.out.println("=="+ts.b);
        
    }
}

then the result is sometimes
m2
M1
= 1000
baked 1000
sometimes it is
m2
M1
= 2000
baked 1000

this makes me have a big head. I only add an output statement. Why will it change if I add it? With the addition of "synchronized", what is the order in which the code is executed? I don"t understand.

Dec.13,2021

is nothing more than the execution of the one who grabs the lock first. no, no, no. In your first case, there is only one output, but there are not enough tests.


the print statement in the

main method does not have Synchronize, so you can only ensure that it is executed after m2, and there is no guarantee about the order between it and M1.


M1 m2 methods all add the synchronized keyword. T.start () and ts.m2 () use the same object ts here. When one thread acquires the lock execution, the other can only wait, and it is uncertain who acquires the lock first.

Menu