/* * 从运行结果看,当m1()方法被锁定后,m2()方法仍然可以执行。 * 而且b的值被改变。由此可以得出结论: * sychronized 只是防止其定义的代码段被同时调用。 * */ public class Test implements Runnable{ 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 { Test t = new Test(); Thread th = new Thread(t); th.start(); Thread.sleep(1000);//确保线程启动 t.m2(); } } /* 运行结果: 1000 b = 1000 */
/* * 从运行结果看,当m1()方法被锁定后,m2()方法仍然可以执行。 * 而且b的值被改变。由此可以得出结论: * sychronized 只是防止其定义的代码段被同时调用。 * 将m2()锁定后,更改部分代码结果??? * */ public class Test 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 { Test t = new Test(); Thread th = new Thread(t); th.start(); Thread.sleep(1000);//确保线程启动 t.m2(); System.out.println(t.b); } } /* 运行结果: b = 1000 2000 */