• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Sychronizing methods

 
Ranch Hand
Posts: 49
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Rancher
Posts: 43081
77
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • 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: 43081
77
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
You guys haven't done this much, have ya? I suggest you study this tiny ad:
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic