第九章 Java多线程机制 05_线程同步_4

来源:互联网 发布:债券数据 编辑:程序博客网 时间:2024/04/26 21:56

鱼欲遇雨:每日都学习一点,持之以恒,天道酬勤!不能用电脑时,提前补上!(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.javapublic 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();}}

答案是可以的!

原创粉丝点击