简体   繁体   中英

synchronization and synchronized block in java

I've got a few questions about synchronization in java.

public class A {

    private int i;

    public A (int t) { i = t; }

    public synchronized void increment() {
        i++;
    }

    public synchronized void decrement() {
        i--;
    }
}

Suppose I have a class implemented as above and I create an object (p) of type A.

I know there can only be one thread executing p.increment(), but is possible for another thread to execute p.decrement() at the same time ?

Thanks~

不能。将synchronized作为方法修饰符等效于将方法包装为synchronized(this)

synchronized does not protect methods. synchronized does not protect objects. synchronized does one thing, and one thing only.

The way you wrote your increment method is actually just a shorthand way of writing this:

public void increment() {
    synchronized(this) {
        i++;
    }
}

This longer way of expressing it make it clear that synchronized is operating on this .

So, the one thing that synchronized does is: The JVM will not allow two threads to be synchronized on the same object at the same time.

If you have an object, p, of type A, then the answer is "no". The JVM will not allow one thread to do the increment at the same time the other thread does the decrement because both threads would be trying to synchronize on the same object, p.

On the other hand, if you have one object p and another object q, both of type A, then one thread could be in a p.increment() call while another thread is in the q.decrement() call. That's because each thread would be synchronized on a different object, and that is allowed.


PS: synchronized actually does one other thing that pertains to the Java concept called "Happens Before". That's something you should learn about (Google is your friend) before you get much deeper into multi-threaded programming.

No. the synchronized will not allow multiple threads to enter the methods for an instance of the object. Note if you have a p1 AND a p2 of class A you could have p1.increment() running at same time p2.decrement() (etc.) is running.

Actually since the value is wrapped into synchronized methods, it content is also synchronized so no, it won't be executed by another thread.

Note that it can be called by another thread.

Personally, if it is only a matter of decrements/increments, I wouldn't bother synchronizing and would simply use Atomic values .

See documentation

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