level 6
venpro
楼主
先源码
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(10000);
b = 2000;
System.out.println("m2:b="+b);
}
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("main:b="+tt.b);
}
}
输出结果是
m2:b=2000
main:b=1000
b = 1000
这里为什么是m2先获得的锁,明明是t.start以后再执行的m2,t.start之后不是应该马上执行run方法吗,然后就m1拿到锁?而且m2执行完应该是10秒以后了,这个时候应该m1的sleep也结束了,应该输出m1的b才是,为什么之后却是main方法里面的b输出了?
2012年05月12日 14点05分
1
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(10000);
b = 2000;
System.out.println("m2:b="+b);
}
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("main:b="+tt.b);
}
}
输出结果是
m2:b=2000
main:b=1000
b = 1000
这里为什么是m2先获得的锁,明明是t.start以后再执行的m2,t.start之后不是应该马上执行run方法吗,然后就m1拿到锁?而且m2执行完应该是10秒以后了,这个时候应该m1的sleep也结束了,应该输出m1的b才是,为什么之后却是main方法里面的b输出了?