Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

synchronized thread???

 
Tran Tuan Hung
Ranch Hand
Posts: 59
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ]
 
Edward Harned
Ranch Hand
Posts: 291
Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
ahmed yehia
Ranch Hand
Posts: 424
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic