本實驗測試的案例是在內置類中有兩個同步方法,但使用的卻是不同的鎖,打印的結果也是異步的。
/**
* @author wuyoushan
* @date 2017/4/28.
*/
public class OutClass {
static class Inner{
public void method1(){
synchronized ("其他的鎖"){
for (int i = 1; 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();
}
}
}
}
}
/**
* @author wuyoushan
* @date 2017/3/20.
*/
public class Run {
public static void main(String[] args){
final 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=14
B i=15
A i=5
A i=6
B i=16
由于持有不同的“對象監視器”,所以打印結果就是亂序的。
摘選自 java多線程核心編程技術-2.2.14