简体   繁体   English

两个线程进入一个同步块

[英]Two threads enter a synchronized block

I have a block wrapped in synchronized(this), and I see both in Debug mode and in the logs that 2 threads enter this section at the same time.我有一个包含在 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);
    }
}

Logs:日志:

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

As you can see I'm increasing the data member index every time I enter the synchronized block.如您所见,每次进入同步块时,我都会增加数据成员索引。 It should print 3 log lines with each index, but as you can see in the logs, index 1 is printed twice and index 3 is printed 4 times.它应该为每个索引打印 3 行日志,但正如您在日志中看到的那样,索引 1 打印了两次,索引 3 打印了 4 次。

Thanks谢谢

UPDATE : Turns out it was happening because the same thread was entering this method multiple times.更新:原来它正在发生,因为同一个线程多次进入这个方法。 synchronized block only works between different threads.同步块仅适用于不同线程。 how this is happening in a synchronous code is the new mystery.这如何在同步代码中发生是新的谜团。

It looks like your threads use different instances of your StateMachine.看起来您的线程使用 StateMachine 的不同实例。 When you synchronize on this you use that particular instance of you class as a monitor.当您this同步时,您将使用该类的特定实例作为监视器。 That means that tread A will be blocked waiting thread B only if both of them operate the same instance of StateMachine.这意味着只有当它们都操作相同的 StateMachine 实例时,trace A 才会被阻塞等待线程 B。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM