本实验测试是在内置类中有两个同步方法,但使用的却是不同的锁,打印结果也是异步的
package com.cky.bean; /** * Created by edison on 2017/12/9. */ public class OutClass { static class Inner { public void method1(){ synchronized ("其他的锁") { for (int i = 0; i <= 10; i++) { System.out.println(Thread.currentThread().getName() +" i="+i); try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } } } } public synchronized void method2() { for (int i = 11; i <=20 ; i++) { System.out.println(Thread.currentThread().getName() + " i="+i); try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } } } } }
package com.cky.bean; /** * Created by edison on 2017/12/9. */ public class Test2 { public static void main(String[] args) { OutClass.Inner inner = new OutClass.Inner(); Thread t1 = new Thread(new Runnable() { @Override public void run() { inner.method1(); } }, "A"); Thread t2 = new Thread(new Runnable() { @Override public void run() { inner.method2(); } }, "B"); t1.start(); t2.start(); } }
B i=11 A i=0 B i=12 A i=1 B i=13 A i=2 B i=14 A i=3 B i=15 A i=4 B i=16
由于持有不同的对象监视器,所以打印结果就是乱序的。