to define, instantiate, and start new threads using
both java.lang.Thread and java.lang.Runnable.
A thread is
an object of type Thread, defined in java.lang
package. Multi-threading functionality in Java
is supported in four places:
Java virtual machine
There are two ways to
The Thread class implements Runnable interface,
which defines run() method. To create a thread, Thread
class can be extended and the run() method must be
overridden. In this method, the code to be executed by
the thread is defined.
Thread class defines many other methods too, which may
or may not be overridden. In general, Thread should be
extended to create a new thread only if methods other
than run() are to be extended. Otherwise, it is
probably better to implement Runnable interface.
It is the simplest way to create a new thread. This
interface defines only run() method. To implement
Runnable, a class need only implement run(), which is
declared as public and void in Runnable. After the
class that implements Runnable is created, it can be
passed in the constructor of Thread to instantiate an
object of Thread.
Thread class defines start() method, which must be
called on the thread object to start execution of
When a thread is created by extending Thread class, it
inherits run() from Thread and overrides it. To
execute the code defined in its run() method, its
start() method needs to be called.
This registers the thread
with Thread Scheduler. Calling start() does not
immediately cause the thread to run; it just makes it
eligible to run. The thread must still contend for CPU
time with all other threads.
For example, if class MyThread has extended Thread,
this is how the thread is started:
Thread t=new MyThread ();
Though, you can override start() too, but that will
defeat the purpose of extending Thread, since start()
basically initiates a call to run(). If you override
start(), you unwittingly might interfere with this
If a thread has been created by implementing Runnable,
you still need to instantiate an object of type
Thread. Say, for example, that MyThread implements
Runnable. In this case, this is how you create and
start a thread.
MyThread m=new MyThread ();
Thread t=new Thread (m);
This will cause the code defined in run () method of
MyThread to be executed.