Sunday, July 4, 2010

Creating a Thread

Java defines two ways in which threads can be created:


1. Implement the Runnable interface.
2. Extend the Thread class.

Implement the Runnable interface:


Runnable abstracts a unit of executable code. You can construct a thread on any object that implements Runnable.

1. To implement Runnable, a class need only implement a single method called run( ). Inside run( ), you will define the code that constitutes the new thread.

2. After you create a class that implements Runnable, you will instantiate an object of type Thread from within that class.

NewThread=new Thread(Runnable threadOb, String threadName)

 /* threadOb is an instance of a class that implements the Runnable interface. This defines where execution of the thread will begin. threadName is the name of the new thread */

3. After the new thread is created, it will not start running until you call its start( ) method, which is declared within Thread. In essence, start( ) executes a call to run( ).

class MyThread implements Runnable

{
     Thread t;
MyThread()
{
     t = new Thread(this, "Demo Thread");
     t.start();
}

public void run()
{
      Thread.sleep(500);
}
}

Extend the Thread class:


The second way to create a thread is to create a new class that extends Thread, and then to create an instance of that class. The extending class must override the run( ) method, which is the entry point for the new thread. It must also call start( ) to begin execution of the new thread.

class NewThread extends Thread

{
     NewThread()
{
     super("Demo Thread");
     start();
}
public void run()
{
     Thread.sleep(500);
}
}

No comments:

Post a Comment