同期メソッドまたは同期ブロックを使用して異なる結果が生成されるシナリオを観察しました。以下のコードから:
class Callme {
void call(String msg) {
System.out.print("[" + msg);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("]");
}
}
class Caller implements Runnable{
String msg;
Callme target;
Thread t;
public Caller(Callme target, String msg) {
this.target = target;
this.msg = msg;
t = new Thread(this, "Caller thread");
t.start();
}
@Override
public void run() {
synchronized(target) {
target.call(msg);
new Callme().call(msg);
}
}
}
public class Test {
public static void main(String[] args) throws InterruptedException {
Callme obj = new Callme();
new Caller(obj, "thread1");
new Caller(obj, "thread2");
new Caller(obj, "thread3");
Thread.currentThread().join();
}
}
Caller::run メソッドで同期ブロックを使用すると、出力は次のように同期されます。
[thread1]
[thread1]
[thread3]
[thread3]
[thread2]
[thread2]
しかし、同期ブロックの代わりに Callme::call メソッドに同期メソッドを使用すると、出力が同期されません。
[thread1]
[thread1[thread2]
]
[thread3[thread2]
]
[thread3]
私の期待は、「Callme::call」メソッドを呼び出すときに異なるオブジェクトを使用しているため、両方のケースで出力が同期されるべきではないということです
これにより、同期ブロックの概念についての私の理解に疑問が生じましたか?