2.2.14內置類與同步:實驗1

本實驗測試的案例是在內置類中有兩個同步方法,但使用的卻是不同的鎖,打印的結果也是異步的。

/**
 * @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

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容