Tuesday, March 27, 2007

Instantiating, and Starting Threads

The java.lang.Thread class contains the methods to create,start and pause threads.Some basic methods to be known from the Thread class are

1.start()
2.yield()
3.sleep()
4.run()

The 'work to be done' is always put in the run() method.

You can instantiate the thread by two ways.

1.By extending the java.lang.Thread class
2.By implementing the Runnable interface

Mostly you will be using the second one which is a good OO practise.Since java does not allow multiple inheritance , and if you use the first method, you cant inherit from other class.And its also good to extend the java.lang.Thread , only if the class needs to have specialized thread like behaviour.


Constructors in Thread:

1.Thread()
2.Thread(string)
3.Thread(Runnable)
4.THread(Runnable,String)

Where string - Name of the thread , Runnable - Instance of the class that implements Runnable

Even though you instantiate the thread , it doesnot enter the runnable state. In order to run the thread , we need to call the thread.start() method.

For example , when you extend a Thread ,syntax is

Thread t1=new Thread();
t1.start();

Eventhough you implement the Runnable interface , an instance of java.lang.Thread is needed to run the thread , by using the thread.start() method.

For example , when you implement the Runnable interface ,

The following is legal ,but does not start a separate thread

ClassName r = new ClassName();
r.run();

(ClassName -The one that implements Runnable interface)

In order to start the thread , replace the above code by below one.

ClassName obj=new ClassName();
Thread t1=new Thread(obj);
t1.start();


As soon as start() method is called , the following takes place.

* A new thread of execution starts (with a new call stack).
* The thread moves from the new state to the runnable state.
* When the thread gets a chance to execute, its target run() method will run.

No comments: