public class TT 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(2500);
b = 2000;
}
public void run() {
try {
m1();
} catch(Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) throws Exception {
TT tt = new TT();
Thread t = new Thread(tt);
t.start();
tt.m2();
System.out.println(tt.b);
}
}
最后输出:
1000
b = 1000
也就是说m2() 先于m1()完成。
m2,m1都有synchronized,m1自己创建了新线程,m2用的是main里的线程
m1的线程和main的线程交替进行,当执行m1后,m1锁住,线程sleep 5s
切换进程2,此时可以执行m2? |
|