Win a copy of Cross-Platform Desktop Applications: Using Node, Electron, and NW.js this week in the JavaScript forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Thread  RSS feed

 
pankaj patil
Ranch Hand
Posts: 98
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Why there r 2 wys to create Thread
 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Basically, if a class is already a subclass of something other than Thread, then it cannot extend Thread because multiple inheritance is not allowed. So it can simply implement the Runnable interface instead.

(Actually, I read an interesting argument for avoiding the extension of Thread and making it a practice to always implement Runnable instead, but I forgot the rationale. :roll: I think this was in one of the Core Java books, so I'll try to find that tonight.)
 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
From page 9 of Core Java 2, Volume II - Advanced Features (7th ed.) by Cay S. Horstmann and Gary Cornell, after presenting the Runnable approach to creating threads...
You can also define a thread by forming a subclass of the Thread class... However, this approach is no longer recommended. You should decouple the task that is to be run in parallel from the mechanism of running it. If you have many tasks, it is too expensive to create a separate thread for each one of them. Instead, you can use a thread pool...

Thread pools are new with Java 1.5 (see API - ThreadPoolExecutor), but the idea of separating the task from the mechanism is a compelling argument even if you're not using 1.5 yet.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!