*
The moose likes Threads and Synchronization and the fly likes Thread or Runnable Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of OCM Java EE 6 Enterprise Architect Exam Guide this week in the OCMJEA forum!
JavaRanch » Java Forums » Java » Threads and Synchronization
Bookmark "Thread or Runnable" Watch "Thread or Runnable" New topic
Author

Thread or Runnable

Ravi Shankarappa
Ranch Hand

Joined: Jan 09, 2010
Posts: 55
I understand implementing Runnable is preferable to extending Thread. In one of the Java sites I came across the following statement:
"The second way is to create the thread and supply it an object with a run() method. This object will be permanently associated with the thread. The object's run() method will be invoked when the thread is started. This method of thread creation is useful if you want many threads sharing an object."

Whats does "..many thread sharing an object mean" if the class is listening on a tcp socket? If I make 5 instances of a class that is listening on a tcp socket and implements Runnable, are there 5 sockets or 1 socket shared between 5 instances?
Would the bytes coming in get split between 5 instances?
Apologise for the real dumb question.

regards
Ravi
Jeff Verdegan
Bartender

Joined: Jan 03, 2004
Posts: 6109
    
    6

Ravi Shankarappa wrote:
I understand implementing Runnable is preferable to extending Thread.


Yes. About the only time it makes sense to extend Thread is for an anonymous inner class when you don't want the extra layer of the anonymous Runnable implementation. And really, that's just convenience, not good design.


Whats does "..many thread sharing an object mean"


They're talking about the case where your Runnable is structured such that it makes sense for multiple threads to invoke the run() method on the same instance of your Runnable. For this to work, either it must not maintain any state of its own, or access to that state must be properly synchronized, and it must make sense for multiple threads to be access/updating that state.

if the class is listening on a tcp socket? If I make 5 instances of a class that is listening on a tcp socket and implements Runnable, are there 5 sockets or 1 socket shared between 5 instances?


That depends on how you write yoru class. Having one Socket shared among multiple threads would probably be a bad idea though (except for one thread to read and one thread to write).

Would the bytes coming in get split between 5 instances?


It depends on how you write the code to read from the Socket.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Thread or Runnable