两个线程进入一个同步块

问题描述 投票:-2回答:1

我有一个包装在synchronized(this)中的块,并且在调试模式和两个线程同时进入此部分的日志中都可以看到。

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次。

谢谢

UPDATE:原来是因为同一线程多次进入此方法而发生的。同步块仅在不同线程之间起作用。这在同步代码中如何发生是一个新的谜。

java android synchronization race-condition synchronized
1个回答
1
投票

看来您的线程使用StateMachine的不同实例。当您在this上进行同步时,您将使用该类的特定实例作为监视器。这意味着仅当胎面A和A都操作相同的StateMachine实例时,它们才会被阻塞,等待线程B。]

© www.soinside.com 2019 - 2024. All rights reserved.