Alex Rivera | Logout

Java two synchronized methods in one instance

Asked 2012-05-13T11:39:04.590
13

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();
}
Edit
Report

1 Answer

2

does this means that increment() and decrement() methods will wait for each other to finish or not?

NO, it means that no other thread will be able to call increment() and decrement() when one thread is within them. To be complete, other thread could not execute any synchronized method of this instance/object

You could call any other synchronized method from a synchronized one without lock on the same instance/object

answered 2012-05-13T18:38:14.630

Your Answer