简体   繁体   中英

When I call a method not synchronized from a synchronized what appen?

if I have two thread A and B that use the same class C.java what happens if thread A use a synchronized method( synchro() ) that access use another class method( myMethod() ) and after 1ms or minus thread B try to use myMethod() ? He will wait until thread A has finished or it accesses to myMethod() ? Thread A and Thread B use the same class instance.

Synchronization is not implicitly transitive . It is merely a lock on the object to execute a block of code. It does not lock the objects that are used inside the code block.

Thread B will have access to the unsynchronized method. Since it's not synchronized, Thread B doesn't need to wait to acquire an object monitor.

Implicit mutex lock will be introduced only for method synchro() , but not for myMethod() , since myMethod() is not synchronized. As a consequence access to myMethod() will not be syncronized between multiple threads.

It will access it.

Only synchronized methods or synchronized blocks cannot be executed concurrently: Synchronized Methods

There is no such thing as a synchronized method.

Repeat after me: There is no such thing as a synchronized method.

When you write this:

synchronized Foobar myFunk() { ... }

That's just syntactic sugar that saves you from having to write this instead:

Foobar myFunk() {
    synchronized(this) { ... }
}

But the second one makes it more obvious what is really going on: It's not the method that is synchronized, it's the object .

The JVM will not allow two different threads to synchronize the same object at the same time. That's all it means. Synchronizing an object does not "lock" the object (other threads can still modify it). Synchronizing an object does not prevent other threads from calling the same method. All it does is prevent other threads from synchronizing the same object at the same time.

How you use that feature is up to you.

Normally, you use it to protect invariants . An invariant is an assertion that you make about some value or some group of values. (eg, the length of list L is always even). If one thread must temporarily break the invariant (eg, by first adding one thing to the list, and then adding another), and some other thread will crash and burn if it sees the broken invariant; then you need synchronization.

The first thread only breaks the invariant while inside a synchronized block, and any other thread only looks at the data when it is synchronized on the same object. That way, the one the looks can never see the invariant in the broken state.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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