File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Threads and Synchronization and the fly likes synchronized thread??? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Threads and Synchronization
Bookmark "synchronized thread???" Watch "synchronized thread???" New topic

synchronized thread???

Tran Tuan Hung
Ranch Hand

Joined: Apr 08, 2007
Posts: 59
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;

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

Joined: Sep 19, 2005
Posts: 291

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

Ed's latest article: A Java Reactive Generator
ahmed yehia
Ranch Hand

Joined: Apr 22, 2006
Posts: 424
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.
I agree. Here's the link:
subject: synchronized thread???
It's not a secret anymore!