Wednesday, 5 June 2013

Creating and running threads

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
                             greetings.start();

The purpose of the start() method is to create the new thread of control that will execute the thread object’s run() method. The new thread runs in parallel with the thread in which start() method was called, along with any other threads that already existed. The start() methods returns immediately after starting the new thread of control, without waiting for the thread to terminate.

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.
For example:-

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);
                   greetingsThread.start();

The advantage of doing this way is that any object can implement the Runnable interface and can contain a run() method that can executed in a separate thread. That run() method has access to everything in the class, including private variables and methods.

No comments:

Post a Comment