Go4Expert

Go4Expert (http://www.go4expert.com/)
-   Java (http://www.go4expert.com/articles/java-tutorials/)
-   -   Creating a Java Thread by extending Thread Class (http://www.go4expert.com/articles/creating-java-thread-extending-thread-t4183/)

Sanskruti 6May2007 21:46

Creating a Java Thread by extending Thread Class
 
A thread can be created in Java programs in two ways – by extending Thread class and by implementing Runnable interface. In case, where the class extends a Tread class, it must override run() method of the Thread class. The program may override the other methods also. If the program uses Runnable interface, it needs to implement only run() method.

The first way to create a thread is to create a subclass of the Thread class. This class must override the run( ) method as discussed above and it may override the other methods too. Then the class that needs the thread can create an object of the class that extends thread class. Following listing shows these steps clearly.

Code: Java

class MyThread extends Thread
{
    MyThread ( )
    {
        …………..
        …………..
    }
   
    public void run ( ) //must override
    {
        ………….
        ………….
    }
    ………..
}

public class Example1
{
    public static void main()
    {

        MyThread t = new MyThread ();
        ………….
        t.start () ;
        ………….
    }
}

Let us now write a program that creates a thread that prints a string n number of times. This program creates the thread by extending thread class:

Code: Java

class PrintString1
{
    public static void main(String args[])
    {
        StringThread1 t = new StringThread1 ("Java",50);
        t.start ( );
    }
}

class StringThread1 extends Thread
{
    private String str;
    private int num;

    StringThread1 (String s, int n)
    {
        str=new String (s);
        num=n;
    }
   
    public void run ( )
    {
        for (int i=1; i<=num; i++)
            System.out.print(str + " ");
    }
}

Program in above listing creates a class called StringThread1 which is a subclass of Thread class. The run method of this class prints a string n number of times. The main class PrintString1 creates an object (thread) of StringThread1 class and uses the start ( ) method to run the thread that print the string “Java” 50 number of times.

Output is:
Code:

Java Java Java Java Java Java Java Java Java Java Java Java Java Java Java Java
Java Java Java Java Java Java Java Java Java Java Java Java Java Java Java Java
Java Java Java Java Java Java Java Java Java Java Java Java Java Java Java Java
Java Java

A better way to create a thread in Java is to implement Runnable interface.

Creating a Java Thread by implementing Runnable Interface >>


All times are GMT +5.5. The time now is 02:17.