• Post Reply Bookmark Topic Watch Topic
  • New Topic

Sychronizing methods

 
Poonam Kadu
Ranch Hand
Posts: 49
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Friends,
If I'm using Runnable Interface to create threads,
is it logically correct to synchronize the run() method,if yes what are the cases when this is done.

cheers,
Poonam K.
 
Ulf Dittmer
Rancher
Posts: 42970
73
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Without knowing anything about what the code does it's hard to say whether synchronization measures are needed. Generally, you need to synchronize accesses to mutable, shared data. If the thread doesn't use any, then there's no need to synchronize. Furthermore, synchronizing all of the run method is probably overkill, but it's impossible to say without seeing the code.
 
Poonam Kadu
Ranch Hand
Posts: 49
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I've not written any code,I just thought of a possibility.
If there is a situation where I want only one thread to be executed as a whole,then may be i can syncronize the run method.

Can you explain this code to me

Thread t = new Thread(id) {
public void run() {
System.out.println(id);
}
};

Thanks
POonam K.
 
Ulf Dittmer
Rancher
Posts: 42970
73
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Synchronizing the run method would not ensure that only a single copy of it ever runs simultaneously. Synchronization happens with respect to an object, and for synchronized methods that objects happens to be the class instance. If you want to make sure that only a single "instance" of the run method is ever run simultaneously, you need to synchronize on some global object, e.g. Thread.class.

The chapter on concurrency of the Java Tutorial talks about these concepts in more detail.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!