Java synchronized method

前端 未结 3 886
我在风中等你
我在风中等你 2020-12-23 16:47

Consider this code:

public synchronized void onSignalsTimeout(List specs) {
    if (specs != null && specs.size() > 0) {
                


        
3条回答
  •  醉话见心
    2020-12-23 17:19

    Yes, other threads can access the objects used in the method; the synchronized keyword guarantees that no more than one thread at the time can execute the code of the method.

    From https://docs.oracle.com/javase/tutorial/essential/concurrency/syncmeth.html:

    • First, it is not possible for two invocations of synchronized methods on the same object to interleave. When one thread is executing a synchronized method for an object, all other threads that invoke synchronized methods for the same object block (suspend execution) until the first thread is done with the object.
    • Second, when a synchronized method exits, it automatically establishes a happens-before relationship with any subsequent invocation of a synchronized method for the same object. This guarantees that changes to the state of the object are visible to all threads. Note that constructors cannot be synchronized — using the synchronized keyword with a constructor is a syntax error. Synchronizing constructors doesn't make sense, because only the thread that creates an object should have access to it while it is being constructed.

提交回复
热议问题