Page 374 - CITS - Computer Software Application -TT
P. 374
COMPUTER SOFTWARE APPLICATION - CITS
Thread th1 = new Thread(r1, “My new thread”);
// the start() method moves the thread to the active state
th1.start();
// getting the thread name by invoking the getName() method
String str = th1.getName();
System.out.println(str);
}
}
Output
My new thread
Now the thread is running ...
Java Runnable Interface
Java runnable is an interface used to execute code on a concurrent thread. It is an interface which is implemented
by any class if we want that the instances of that class should be executed by a thread.
The runnable interface has an undefined method run() with void as return type, and it takes in no arguments. The
method summary of the run() method is given below-
Method Description
public void run() This method takes in no arguments. When the
object of a class implementing Runnable class is
used to create a thread, then the run method is
invoked in the thread which executes separately.
The runnable interface provides a standard set of rules for the instances of classes which wish to execute code
when they are active. The most common use case of the Runnable interface is when we want only to override the
run method. When a thread is started by the object of any class which is implementing Runnable, then it invokes
the run method in the separately executing thread.
A class that implements Runnable runs on a different thread without subclassing Thread as it instantiates a
Thread instance and passes itself in as the target. This becomes important as classes should not be subclassed
unless there is an intention of modifying or enhancing the fundamental behavior of the class.
Runnable class is extensively used in network programming as each thread represents a separate flow of control.
Also in multi-threaded programming, Runnable class is used. This interface is present in java.lang package.
Implementing Runnable
It is the easiest way to create a thread by implementing Runnable. One can create a thread on any object by
implementing Runnable. To implement a Runnable, one has only to implement the run method.
public void run()
In this method, we have the code which we want to execute on a concurrent thread. In this method, we can use
variables, instantiate classes, and perform an action like the same way the main thread does. The thread remains
until the return of this method. The run method establishes an entry point to a new thread.
How to create a thread using Runnable interface
To create a thread using runnable, use the following code-
1 Runnable runnable = new MyRunnable();
2
361
CITS : IT&ITES - Computer Software Application - Lesson 101 - 108 CITS : IT&ITES - Computer Software Application - Lesson 101 - 108