在下面的代碼,我試圖找出線程在synchronized塊處理執行:線程執行序列
public class ThreadExp {
public static void main(String[] args) throws InterruptedException {
MyRunnable r = new MyRunnable();
Thread t1 = new Thread(r, "Thread1");
Thread t2 = new Thread(r, "Thread2");
t1.start();
t2.start();
}
}
class MyRunnable implements Runnable {
@Override
public void run() {
callFn();
}
private void callFn() {
System.out.println(Thread.currentThread().getName() + ": entered callSync()");
synchronized (Thread.currentThread()) {
System.out.println(Thread.currentThread().getName() + ": inside sync");
try {
Thread.currentThread().sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + " leaving sync");
}
System.out.println(Thread.currentThread().getName() + ": leaving callSync()");
}
}
實際輸出:
Thread1: entered callFn()
Thread2: entered callFn()
Thread1: inside sync block
Thread2: inside sync block
// 5000 millisec sleep
Thread2 leaving sync block
Thread1 leaving sync block
Thread2: leaving callFn()
Thread1: leaving callFn()
而我預期的東西如:
Thread1: entered callFn()
Thread2: entered callFn()
Thread1: inside sync block
// 5000 millisec sleep
Thread1 leaving sync block
Thread1: leaving callFn()
Thread2: inside sync block
Thread2 leaving sync block
Thread2: leaving callFn()
總的來說,我認爲Thread1會獲得鎖,然後進入睡眠。只有在線程1完成後,線程2才能進入同步塊。
同步線程對象將永遠不會阻塞。它怎麼可能?多線程嘗試輸入鎖時發生爭用,但在您的情況下,每個線程正在輸入唯一的鎖。 – dlev