0
我觀察到使用同步方法或同步塊產生不同結果的場景。 從下面代碼:同步方法和塊的行爲不同
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();
}
}
當我使用同步塊在來電::運行方法的輸出中被如下同步:
[thread1]
[thread1]
[thread3]
[thread3]
[thread2]
[thread2]
但是當我使用了的CallMe同步方法: :呼叫的方法,而不是同步塊時,輸出不同步:
[thread1]
[thread1[thread2]
]
[thread3[thread2]
]
[thread3]
我的期望是在輸出不應該在這兩種情況下貝科同步使用我在調用「Callme :: call」方法時使用不同的對象
這讓我質疑我對Synchronized塊概念的理解嗎?