鱼欲遇雨:每日都学习一点,持之以恒,天道酬勤!不能用电脑时,提前补上!(2012.9.3)
java的一道面试题
public class TT {
private int b = 100;
public synchronized void m1() throws Exception {
b = 1000;
Thread.sleep(5000);
System.out.println("b = " + b);
}
public void m2() {
System.out.println(b);
}
}
问,当方法m1()锁定的时候,可不可以调用m2()?输出b的值
代码示例:
// TT.java
public class TT implements Runnable {
private int b = 100;
public synchronized void m1() throws Exception {
b = 1000;
Thread.sleep(5000);
System.out.println("b = " + b);
}
public void m2() {
System.out.println(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();
Thread.sleep(1000);
tt.m2();
}
}
答案是可以的!