2016-10-10 11 views
0

私は、同期化機能を持つクラスcを持っていますm1m2m3です。私は同じクラスの3つの異なるインスタンスを作成しましたc1,c2,c3それぞれ異なるスレッドで実行していますt1,t2t3それぞれ。もしt1アクセスm1t2t3アクセスm1 ??同じクラスの異なるオブジェクトの同期メソッド

答えて

1

に依存します。メソッドが静的である場合、それらはクラスオブジェクト上で同期し、インタリーブは不可能である。静的でない場合は、thisで同期します。オブジェクトとインターリーブが可能です。次の例では、動作を明確にする必要があります。

import java.util.ArrayList; 
import java.util.List; 

class Main { 
    public static void main(String... args) { 
    List<Thread> threads = new ArrayList<Thread>(); 

    System.out.println("----- First Test, static method -----"); 
    for (int i = 0; i < 4; ++i) { 
     threads.add(new Thread(() -> { 
     Main.m1(); 
     })); 
    } 
    for (Thread t : threads) { 
     t.start(); 
    } 
    for (Thread t : threads) { 
     try { 
     t.join(); 
     } catch (InterruptedException e) { 
     e.printStackTrace(); 
     } 
    } 

    System.out.println("----- Second Test, non-static method -----"); 
    threads.clear(); 
    for (int i = 0; i < 4; ++i) { 
     threads.add(new Thread(() -> { 
     new Main().m2(); 
     })); 
    } 
    for (Thread t : threads) { 
     t.start(); 
    } 
    for (Thread t : threads) { 
     try { 
     t.join(); 
     } catch (InterruptedException e) { 
     e.printStackTrace(); 
     } 
    } 

    System.out.println("----- Third Test, non-static method, same object -----"); 
    threads.clear(); 
    final Main m = new Main(); 
    for (int i = 0; i < 4; ++i) { 
     threads.add(new Thread(() -> { 
     m.m2(); 
     })); 
    } 
    for (Thread t : threads) { 
     t.start(); 
    } 
    for (Thread t : threads) { 
     try { 
     t.join(); 
     } catch (InterruptedException e) { 
     e.printStackTrace(); 
     } 
    } 
    } 

    public static synchronized void m1() { 
    System.out.println(Thread.currentThread() + ": starting."); 
    try { 
     Thread.sleep(1000); 
    } catch (InterruptedException e) { 
     e.printStackTrace(); 
    } 
    System.out.println(Thread.currentThread() + ": stopping."); 
    } 

    public synchronized void m2() { 
    System.out.println(Thread.currentThread() + ": starting."); 
    try { 
     Thread.sleep(1000); 
    } catch (InterruptedException e) { 
     e.printStackTrace(); 
    } 
    System.out.println(Thread.currentThread() + ": stopping."); 
    } 
} 

詳細については、this oracle pageを参照してください。

+0

Aaah ....私の悪いところを完全に忘れてしまった。 –

+0

@ KAY_YAK、この回答があなたの問題を解決した場合は、それを受け入れたものとしてマークしてください。 –

関連する問題