Does the following mean that only ONE thread can be in ANY method of the object? Or can a multiple threads be in DIFFERENT methods just not the same one? Why?

public class SynchronizedCounter {
    private int c = 0;

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

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

    public synchronized int value() {
        return c;
    }
}
有帮助吗?

解决方案

Does the following mean that only ONE thread can be in ANY method of the object?

For your specific example, yes, because all the methods are synchronized and non-static.

If your class had any unsynchronized methods, then the unsynchronized methods would not be blocked.

If your class used synchronized blocks instead of methods and synchronized them on different locks, it could get much more complex.

其他提示

Does the following mean that only ONE thread can be in ANY method of the object?

Yes. Non-static synchronized methods implicitly synchronize on this. It's equivalent to:

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

If this were a real piece of code (I know it's not), I would recommend throwing out your SynchronizedCounter class entirely and using AtomicInteger instead.

Of course, they are synchronized on the this object. If you had written your own synchronized block with different objects for the different methods you have then it won't be the case.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top