Java 两个线程进入一个同步块

Java 两个线程进入一个同步块,java,android,synchronization,race-condition,synchronized,Java,Android,Synchronization,Race Condition,Synchronized,我在synchronized(这个)中包装了一个块,我在调试模式和日志中看到两个线程同时进入这个部分 public void dispatch(Event.Builder eventBuilder) { synchronized (this) { index++; getLogger().d(TAG, "race condition line A - The index is " + index); try {

我在synchronized(这个)中包装了一个块,我在调试模式和日志中看到两个线程同时进入这个部分

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);
    }
}
日志:

如您所见,每次进入同步块时,我都在增加数据成员索引。 它应该用每个索引打印3行日志, 但正如您在日志中看到的,索引1打印了两次,索引3打印了4次

谢谢

更新
事实证明,这是因为同一线程多次进入此方法。同步块仅在不同线程之间工作。这在同步代码中是如何发生的是一个新的谜团。

看起来您的线程使用的是状态机的不同实例。当您在
上同步此
时,您使用类的特定实例作为监视器。这意味着,只有当两个线程都操作同一个StateMachine实例时,线程A才会被阻塞等待线程B。

在运行时,你有多个
StateMachine
实例吗?@Michael一个对另一个说:“啊,你。好像我没有足够的资源来应付。”我编辑并用文本代码替换了截图。我使用的是这个类的一个子类,它是单音。当然不是多个实例
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