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();
}
Yes, the
synchronizedkeyword is a shorthand for: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
SynchronizedCountershould implementRunnablerather than extending aThreadsince you are passing it to other thread’s constructor – now it is a bit confusing.