The main program
i have created a class called counter and initialized a variable c . When called on increment method it increments by 1. When called on decrement method it decreases by 1.
There is one more method called getVal which will return the c value. These methods i have added synchronized keyword for the methods
In the main program i am sharing the counter object in the loop. I am looping and creating threads and starting them but while running even though i have added synchronized method iam getting output like this
the increment case Thread--->72
the value case Thread--->72
Thread--->72 incremented 1
the decrement case Thread--->72
the value case Thread--->72
Thread--->72 decremented 0
the increment case Thread--->76
the value case Thread--->76
Thread--->76 incremented 1
the decrement case Thread--->76
the value case Thread--->76
Thread--->76 decremented 0
the increment case Thread--->80
the value case Thread--->80
Thread--->80 incremented 1
the increment case Thread--->22
the increment case Thread--->124
the increment case Thread--->2
the increment case Thread--->116
the value case Thread--->116
the increment case Thread--->120
the value case Thread--->120
Thread--->120 incremented 6
the decrement case Thread--->120
Thread 72 and Thread 76 are printing correctly first it is increasing the value so it is 1 and then decreasing value so it is 0.
but if you see Thread 22 and Thread 124 and Thread 2 and so on the value of c variable reached to 6 . This is what iam confused even though adding synchronized keyword it is behaving very different
But if i add synchronized block like this in run
iam getting the expected output .Why it is happening , whether the synchronized keyword for those methods are not enough?do i have to use the synchronize for run only?
Can someone explain about re entrancy according to this code?