[英]Two threads enter a synchronized block
我有一個包含在 synchronized(this) 中的塊,並且我在調試模式和日志中都看到有 2 個線程同時進入此部分。
public void dispatch(Event.Builder eventBuilder) {
synchronized (this) {
index++;
getLogger().d(TAG, "race condition line A - The index is " + index);
try {
Event event = eventBuilder.build();
getLogger().d(TAG, "race condition line B - The index is " + index);
mDispatcher.dispatch(event);
} catch (InstantiationWithoutBuilderException e) {
// Dev time Exception. Should be caught by Developer
throw e;
} catch (StateMachineException e) {
if (!e.wasWrittenToErrorHistory()) {
printError(new ExceptionHistoryElement(mState, eventBuilder.getTemporaryEventWithTypeForException(), e));
}
} catch (Exception e) {
printError(new ExceptionHistoryElement(mState, eventBuilder.getTemporaryEventWithTypeForException(), e));
}
getLogger().d(TAG, "race condition line C - The index is " + index);
}
}
日志:
race condition line A - The index is 1
race condition line B - The index is 1
race condition line A - The index is 2
race condition line B - The index is 2
race condition line C - The index is 2
race condition line A - The index is 3
race condition line B - The index is 3
race condition line C - The index is 3
race condition line C - The index is 3
race condition line A - The index is 4
race condition line B - The index is 4
race condition line C - The index is 4
race condition line A - The index is 5
race condition line B - The index is 5
race condition line C - The index is 5
如您所見,每次進入同步塊時,我都會增加數據成員索引。 它應該為每個索引打印 3 行日志,但正如您在日志中看到的那樣,索引 1 打印了兩次,索引 3 打印了 4 次。
謝謝
更新:原來它正在發生,因為同一個線程多次進入這個方法。 同步塊僅適用於不同線程。 這如何在同步代碼中發生是新的謎團。
看起來您的線程使用 StateMachine 的不同實例。 當您this
同步時,您將使用該類的特定實例作為監視器。 這意味着只有當它們都操作相同的 StateMachine 實例時,trace A 才會被阻塞等待線程 B。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.