In java, a thread is represented by an object belonging to the class java.lang.thread(or to a subclass of this class). The pupose of a thread object is to execute a single method and to execute it just once. This metod represents the task to be carried out by the thread.
There are two ways to program a thread.
One is to create a subclass of thread and to define the method public void run() in the subclass. This run() method defines the task that will be performed by the thread. For example, here is a simple, class that defines a thread that does nothing but print a message on standard output:
To use Named Thread, you must of course create an object belonging to this class. For example,
Named Thread greetings = new Named Thread (“Fred”);
However creating the object does not automatically start the thread running or cause its run() method to be executed. To do that, you must call the start() method in the thread object. For example, would be done with the statement
The second is to define a class that implements the interface java.lang.Runnable. The runnable interface defines a single method, public void run(). Given a runnnable, it is possible to create a thread whose task is to execute the Runnable’s run() method.
The thread class has a constructor that takes a Runnable as its parameter when an object that implements the Runnable interface is passed to that constructor, the run() method of the thread will simply call the run() method from the Runnable, and calling the thread’s start() method will create a new thread of control in which Runnable’s run() method is executed.
to use this version of class, we would create a NamedRunnable object and use that object to create an object of type thread:
NamedRunnable greetings = new NamedRunnable(“Fred”);
Thread greetings Thread = new Thread (greetings);