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
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.