How To Create Thread In Java

 Posted On  | Yashwant Chavan 

Thread is nothing but the instance of Thread class defined in java.lang package. Its individual process which execute on separate stack. With the help of Thread you can perform the multiple tasks simultaneously.

How to create a Thread?

There are two ways to create a Thread instance, By extending Thread class and another way is by implementing the Runnable Interface. Both the examples are given below.

run() Method?

When you define Thread , you need to override the run() method. All action (Business logic) happens in run() method. But mentioned method look like ordinary method nothing special about this method which treat it as Thread. When you start the thread using start() method, it invokes the run() method and it is going to execute method on separate call stack. At this moment it become a Thread.

ThreadExample.java

Extends Thread class, In main() method we call the start() method on thread instance. Which calls overloaded run() method internally. This approach is not good in terms of Object oriented prospective, because then you can not extend other class.

package com.technicalkeeda.app;

public class ThreadExample extends Thread {

    @Override
    public void run() {
        System.out.println("Using Thread class...");
    }

    public static void main(String[] args) {
        ThreadExample myThread = new ThreadExample();
        myThread.start();
    }

}

RunnableExample.java

Implements the Runnable interface, When you implements the Runnable interface you need to override the run() method. You can use same target class object (RunnableExample) for multiple threads also. i.e. Several Thread class use the same target job.

package com.technicalkeeda.app;

public class RunnableExample implements Runnable {

    @Override
    public void run() {
        System.out.println("Thread Using Runnable Interface..");
    }
}

Pass you runnable instance to thread class.

package com.technicalkeeda.app;
public class ThreadTest {

    public static void main(String[] args) {
        RunnableExample runnableExample = new RunnableExample();
        Thread t1 = new Thread(runnableExample); // "runnableExample" same target for multiple threads
        ThreadExample t2 = new ThreadExample();
        t1.start();
        t2.start();
    }

}

start() method?

Lots of things happens , when you call start method on thread instance. 1] New thread of execution starts 2] It moves from "new state" to "runnable state", We will see the Thread states in separate article. 3] When thread enters in "runnable state", its eligible to get chance to execute the run method.

output

Thread Using Runnable Interface..
Using Thread class...


© technicalkeeda.com 2017

 |  Find us on Google+ |  Rss Feed

Loaded in 0.0318 seconds.