Tuesday, December 7, 2010
Java Threads - Implements Runnable V/s extends Thread
Java Threads - Implements Runnable V/s extends Thread class
Threads are very important part of any computer system, that wants to do multitasking. Threads are called low-weight processes. A process is a program under execution. Program has a text part, data part. It has memory to use for it's execution. Threads share this memory, so communication between threads is very simple and not costlier compared to IPC.
Java provides support for multi threading and also in java it is very easy to play with them.
The below article is for people who already know how to implement a Thread in java. Java gives users, 2 options. Either they have to implement Runnable interface Or they have to extend from Thread class. Only then any class, say "X" can be Thread scheduled.
Thread scheduler is part of OS and not part of JVM. So the ways threads behave changes from platform to platform.
Why do we have 2 ways of creating Thread classes ?
First thing we have to keep in mind that, Java doesn't support multiple inheritance. i.e, "class A extends B,C" is not true, where as "class A implements B,C" is true.
So if a class X extends Thread, then it cannot extend from any parent (So sad :-( ). In order to avoid this, Runnable interface is defined and it is always better to use interfaces than extending from a parent.
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment