I have a problem with my code. I have a class Counter with count variable and the class includes 2 method * add() method to implement count = count+2; * sub() method to implement count = count -1; and....
I would like that every time thread1 only implement add() method and the thread2 only implement only sub() method, so i have to use synchronized , but may be i am stupid so i still not yet clear in the thread. Anyone help me please. Thanks and best regards. [ October 02, 2007: Message edited by: Tran Tuan Hung ]
The synchronized keyword is ineffective for coordinating the threads in your code since each only calls a single method. However, the second attribute of synchronizing is to make sure the variable "count" is updated properly. Therefore, you need this keyword.
The Java Spec is difficult, but the relevant part is chapter 17: See here
In the main method you are creating two Threads but giving them two different runnable instances of the class, so every Thread will acquire the lock on the 'this' instance which is different from the other Thread, hence both run concurrently and dont block each other.
To fix your code in the way you want there could be several solutions, one is to make your synchronized methods static or give the two Threads the same runnable instance.