スレッドの深さのプロファイル1

5026 ワード

同期の特性を探索するためにいくつかの実験を行った.
package com.wjy.synchronize;

public class MyThread implements Runnable{
    @Override
    public void run() {
        // TODO Auto-generated method stub
        synchronized (this) {
            for(int i=0;i<10;i++){
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName()+"   loop   "+i);
            }
        }
        
    }
    
}

synchronizedの識別子を関数宣言の場所に移動するのも同様の効果,すなわちpublic synchronized void run(){....であることが分かった.
しかし、synchronized(this)のthisをMyThreadに変えようと思ったことはありますか.classは?synchronized(MyThread.class)です.
実験結果:同じように見えますが、実はそうではありません.
テストコード:
 
package com.wjy.test;

import com.wjy.synchronize.MyThread;

public class MainTestSyn {
    public static void main(String args[]){
        final MyThread myThread=new MyThread();

        Thread thread1=new Thread(myThread, "buDog");
        Thread thread2=new Thread(myThread, "paoDog");      
  
        thread1.start();
        thread2.start();
    }
}

 
ただし、テストコードを次のように変更します.
package com.wjy.test;

import com.wjy.synchronize.MyThread;

public class MainTestSyn {
    public static void main(String args[]){
        final MyThread myThread=new MyThread();

     final MyThread addThread=new MyThread();


        Thread thread1=new Thread(myThread, "buDog");
        Thread thread2=new Thread(addThread, "paoDog");      
  
        thread1.start();
        thread2.start();
    }
}

これと...classの違い.以上のテストコードを採用すると、thisは同期効果に達しないからです.だからclassとは、すべてのMyThreadのオブジェクトを同期することを意味します.これは、現在のオブジェクトを同期するだけです.