我相信,這是一個簡單的問題,但我仍然不明白。說,我有以下代碼。調用同步方法的順序
Runnable objectRunnable = new Runnable() {
void run() {
synchronized(object) {
for (int i = 0; i < 5; i++) {
System.out.println("it's runnable");
Thread.sleep(100);
}
}
}
};
void doSomething() {
synchronized(object) {
for (int i = 0; i < 5; i++) {
System.out.println("it's doSomething");
Thread.sleep(100);
}
}
}
synchronized (object) {
new Thread(objectRunnable).start();
}
object.doSomething();
因此,輸出類似
it's doSomething
it's doSomething
it's doSomething
it's doSomething
it's doSomething
it's runnable
it's runnable
it's runnable
it's runnable
it's runnable
問題是,爲什麼doSomething()
去線程之前?而且,如果我在同步塊之後多次調用對象方法,它們都會被隨後調用,並且只有程序返回到線程的內容。如果我用同步塊替換那個線程調用線,比如說調用一些模擬對象方法,那麼比一切都好,並按照指定的順序進行。
同步對象本身的方法在執行任何線程之前都有某種優先級,在此對象上同步?
不幸的是,這段代碼不能編譯。 – tkausl