Java two synchronized methods in one instance

java, multithreading, synchronization

Solution

Yes, the `synchronized` keyword is a shorthand for:

synchronized(this) {
  //...
}

So both methods are effectively locking on the same mutex object. If you want them to be independent from each other (which is a bad idea in this example as they both access the same value), see Object locking private class members - best practice? (Java).

BTW your `SynchronizedCounter` should implement `Runnable` rather than extending a `Thread` since you are passing it to other thread's constructor - now it is a bit confusing.

Problem

consider the following code: ``` public class SynchronizedCounter extends Thread { private int c = 0; public synchronized void increment() { c++; } public synchronized void decrement() { c--; } public void run() { for(;;) increment(); } } static void main(String[] args) { SynchronizedCounter counter = new SynchronizedCounter(); counter.start(); for(;;) counter.decrement(); } ``` does this means that increment() and decrement() methods will wait for each other to finish or not? EDIT: and this does not wait? ``` static void main(String[] args) { SynchronizedCounter counter1 = new SynchronizedCounter(); SynchronizedCounter counter2 = new SynchronizedCounter(); counter1.start(); for(;;) counter2.decrement(); } ```

Original source

Related problems