Register Now

Login

Lost Password

Enter your email to reset your password.

BY Author

Java – Creating a Thread

In Java, Thread is created by two ways:
1) By extending a Thread class

         2) By implementing the Runnable interface

1) By extending a Thread class

                             In this type, we create a thread by creating a class that extends a class named Thread.

Example

class UserThread extends Thread
{
    public void run()
    {
        System.out.println("User Thread (Child Thread) Running");
    }
}

class ExtendThread
{
    public static void main(String args[])
    {
        UserThread t = new UserThread();
        t.start();
        System.out.println("Main thread running");
    }
}

Output

Main thread running
User Thread (Child Thread) Running

                                                                             OR

User Thread (Child Thread) Running
Main thread running

Now in the above program, there are two threads. One is the main thread (default thread) created by JVM, and another is child thread created by the programmer at line,

UserThread t = new UserThread();

Child thread executes run() method, and main thread executes rest of the code.
Above program creates two outputs because it depends on thread scheduler that, which thread should be run first and which should be last.
Thread scheduler may execute main thread before or after child thread because by default they both have the same priority, “NORM_PRIORITY” as “5” (Priorities of thread are explained further).

Note

Child thread always inherits the priority of its parent thread if it is not set with priority, explicitly.
In the above program, the main thread has default priority “NORM_PRIORITY” as “5”. So automatically UserThread (Child thread of Main thread) will inherit the priority of Main thread as “5”.

Now let’s have a glance at the life cycle of threads in the above program.

The main thread is automatically created and started by JVM before the creation of child thread. So when the main() method gets the start, the main thread is in running state.

At the line

UserThread t = new UserThread();

UserThread object (as a Child thread) is created. So, it is in new/born state.

After invoking start() method at line

t.start();

UserThread enters into Runnable state.

When UserThread is executing run() method, it is said to be in running state.

If UserThread got chance before executing line

System.out.println("Main Thread Running");

by the main thread.
It means that the main thread has entered into sleeping state for a short time within which UserThread executes run() method.

If the main thread got chance before executing the line

System.out.println("User Thread (Child Thread) Running");

present in run() method.

It means UserThread has entered into the sleeping state for a short time within which main thread executes its work.

When UserThread completes run() method, it enters into dead state.

Similarly, the main thread enters into the dead state after completing its work.

Example – II

class UserThread extends Thread
{
    public void run()
    {
        for(int i=1;i<=5;i++)
        {
            System.out.println("User Thread Running");
        }
    }
}

class ExtendThread
{
    public static void main(String args[])
    {
        UserThread t = new UserThread();
        t.start();
        for(int i=1;i<=5;i++)
        {
            System.out.println("Main Thread running");
        }   
    }
}

Output

Main Thread running
Main Thread running
User Thread Running
User Thread Running
User Thread Running
Main Thread running
Main Thread running
Main Thread running
User Thread Running
User Thread Running

Note

The output may be different for each time we run this above program again because it depends on thread scheduler.

How run() method got execute even if it is not called?

Of course, you might doubt that how run() method got executed even if it is not called.
Actually, the programmer does not call the run() method directly, but JVM calls it from the start() method of thread class.
The programmer only calls start() method of Thread class (Superclass of UserThread class). The start() method of Thread class invokes the run() method (of child class of Thread class) that do not have arguments.

Java Programming Language run method Execution Process in Multithreading

What if the run() method called directly?

The new thread created by the programmer is attached with thread scheduler, only in the start() method of Thread class.
If the programmer did not call start() method of thread class and called run() method directly, then created thread will not be attached with thread scheduler and it will not be treated as a new thread but will be treated as same parent thread.

Thus we will be not able to achieve multithreading.

Let’s check it through the example given below:

Example

class UserThread extends Thread
{
    public void run()
    {
        for(int i=1;i<=5;i++)
        {
            System.out.println("User Thread Running");
        }
    }
}

class DirectRunDemo
{
    public static void main(String args[])
    {
        UserThread t = new UserThread();
        t.run();
        for(int i=1;i<=5;i++)
        {
            System.out.println("Main Thread running");
        }
    }
}

Output

User Thread Running
User Thread Running
User Thread Running
User Thread Running
User Thread Running
Main Thread running
Main Thread running
Main Thread running
Main Thread running
Main Thread running

In this program, an output will always be same as above. It is not a multithreaded program but a single threaded normal program because we have called run() method of class UserThread directly, instead of start() method of thread class.

Note

A new thread is executed, only if run() method without arguments is called from the start() method of Thread class, not directly.

You can also check by using the run() method with arguments and overriding start() method in the class that extends Thread class.

2) Creating a thread by implementing Runnable interface

With this type, we create a thread by creating a class that implements an interface named Runnable.

Example – I

class UserThread implements Runnable
{
    public void run()
    {
        System.out.println("UserThread Running");
    }
}

class ImplementRunnableDemo
{
    public static void main(String args[])
    {
        UserThread u = new UserThread();
        Thread t = new Thread(u);
        t.start();
        System.out.println("Main Running");
    }
}

Output

UserThread Running
Main Running

                                                                                   OR

Main Running
UserThread Running

Above program creates two outputs because it depends on thread scheduler that, which thread should be run first and which should be last.
Both main Thread and UserThread have the same priority.

At line

Thread t = new Thread(u);

You have seen that we have passed the reference ‘u of UserThread to Thread class because it tells the Thread class about the run() method that should be invoked.
Here we have passed a reference of UserThread. Therefore Thread class will call run() method of class UserThread. Otherwise Thread class will call its own empty run() method.

Note

The runnable interface contains only abstract run() method.
Thread class also implements Runnable interface.

Let’s see a more practical example.

Example – II

class UserThread implements Runnable
{
    public void run()
    {
        for(int i=1;i<=5;i++)
        {
            System.out.println("UserThread Running");
        }
    }
}

class ImplementRunnableDemo
{
    public static void main(String args[])
    {
        UserThread u = new UserThread();
        Thread t = new Thread(u);
        t.start();
        for(int i=1;i<=5;i++)
        {
            System.out.println("Main Running");
        }
    }
}

Output

Main Running
UserThread Running
UserThread Running
Main Running
Main Running
Main Running
UserThread Running
UserThread Running
UserThread Running
Main Running

Note

The output may be different for each time we run this program again because it completely depends on thread scheduler.

Best approach to create a thread between extending a Thread class and implementing a Runnable interface

Creating a thread by implementing a Runnable interface is best and easy approach.
Because creating a thread by implementing a Runnable interface also allows a class to extend/inherit another class.
But if we create a thread by extending a Thread class, further we can’t extend any another class because multiple inheritance is not allowed in Java.

 

Leave a reply