我观察到使用同步方法或同步块产生不同结果的场景。从下面的代码:
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”方法时使用了不同的对象
这让我质疑我对同步块概念的理解?