synchronizedの役割(三)

1664 ワード

b、オブジェクトまたはメソッドをロックし、静的である
オブジェクトが属するクラスをロックします.
public synchronized    static void execute(){
      //...
}

に等しい
public class TestThread {
    public static void execute(){
        synchronized(TestThread.class){
            //
          }
      }
}

テスト:
ターゲットクラス:
public class TestThread {
    private static Object lock=new Object();
    public synchronized static void execute(){  //      
        for(int i=0;i<100;i++){
              System.out.println(i);
          }    
      }
    public static void execute1(){
        for(int i=0;i<100;i++){
              System.out.println(i);
          }    
      }
    public void test(){
          execute();     //      ,      
        //execute1();  //      ,      
      }
}

スレッドクラス:異なるメソッドを呼び出し、2つのスレッドクラスを構築します.
public class ThreadA implements Runnable{
    public void run() {
          TestThread.execute();//        
      }
}
public class ThreadB implements Runnable{
    public void run() {
          TestThread test=new TestThread();
          test.test();//          
      }
}

呼び出し:
Runnable runabbleA=new ThreadA();
Thread a=new Thread(runabbleA,"A");                
a.start();
Runnable runabbleB=new ThreadB();
Thread b=new Thread(runabbleB,"B");                
b.start();