Thursday, 18 June 2015

Creating thread in Java

To create a thread we need to instantiate an object of type Thread. Java provides two ways to do that -

  • By implementing the Runnable interface.
  • By extending the Thread class, itself.

Here we'll look at both the ways of creating a thread

Implementing Runnable

One way to create a thread is to implement the Runnable interface.

@FunctionalInterface
Interface Runnable {
    public abstract void run();
}

To implement Runnable, a class has to implement only the run() method. Inside run() method we write the code for the new thread.

Note that, if you are not extending the Thread class, your class object would not be considered a thread object. You have to explicitly create a Thread class object so that run() method of the thread can be executed. For that pass object of class that is implementing Runnable to a Thread in its constructor. Thread defines several constructors, some of the commonly used are.

Thread()
Thread(String name)
Thread(Runnable threadObj)
Thread(Runnable threadObj, String name)

We can use any of the last two in case of Runnable to create a thread.

After the new thread is created, it will not start running until you call the start() method, which is declared within Thread. As soon as start() method is called upon a thread following actions happen

  • The thread's state changes from New state to the Runnable state.
  • Thread's target run() method will execute (depends upon when thread gets the CPU cycle).

Thread creation Example using Runnable

class MyThread implements Runnable{
    MyThread(){
        Thread t = new Thread(this, "My Thread");
        t.start();
    }
    @Override
    public void run() {
        System.out.println("Entered run method " +Thread.currentThread().getName());
        for(int i = 0; i < 5; i++){
            System.out.println("My Thread" + i);
            try {
                Thread.sleep(10);
            } catch (InterruptedException e) {                
                e.printStackTrace();
            }
        }
        System.out.println("Finished with MyThread");
        
    }
    
}

public class ThreadDemo {
    public static void main(String[] args) {        
        MyThread myThread = new MyThread();
        for(int i = 0; i < 5; i++){
            System.out.println("Main thread" + i);
            try {
                Thread.sleep(5);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        System.out.println("Finished with Main Thread");
    }

}

Output

Main thread0
Entered run method My Thread
My Thread0
Main thread1
Main thread2
My Thread1
Main thread3
Main thread4
My Thread2
Finished with Main Thread
My Thread3
My Thread4
Finished with MyThread

Here we are using the constructor Thread(Runnable threadObj, String name) while creating a thread object - new Thread(this, "My Thread"); here this denotes the runnable object.

Calling start() method on the thread will execute the run method where it will print numbers along with the thread name.

Sleep is used to show how main thread and the user created thread are working in tandem. As control can transfer to another thread when the thread on which the sleep is called is sleeping.

Thread creation Example by extending Thread class

Another way to create a thread is to create a class that extends Thread class and then create an instance of that class. The extending class has to override the run() method and also needs to call start() method to start execution of the new thread.

class TestThread extends Thread{
    public TestThread() {
        
    }
    @Override
    public void run(){
        System.out.println("Entered run method " +Thread.currentThread().getName());
        for(int i = 0; i < 5; i++){
            System.out.println("TestThread" + i);
            try {
                Thread.sleep(10);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        System.out.println("Finished with TestThread");
        
    }
}
public class ThreadExtendDemo {

    public static void main(String[] args) {
        TestThread t = new TestThread();
        // starting the thread
        t.start();
        for(int i = 0; i < 5; i++){
            System.out.println("Main thread" + i);
            try {
                // making the thread sleep 
                Thread.sleep(5);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        System.out.println("Finished with Main Thread");
    }

}

Here we are extending the thread class so we just need to create an instance of that class that will be a thread object. Then we are calling start() method on that thread object.

So these are the 2 ways provided in Java to create a new thread.

There are some other ways we can implement the run() method like, as an anonymous class and starting Java 8 using a lambda expression. Lets see how that can be done.

Creating thread as an anonymous class

class InnerThread{
    Thread t;
    // Constructor
    public InnerThread(String name){
        // Anonymous class with run method implemented
        Thread t = new Thread(name){
            @Override
            public void run(){
                System.out.println("Entered run method " +Thread.currentThread().getName());
                for(int i = 0; i < 5; i++){
                    System.out.println(name + i);
                    try {
                        Thread.sleep(10);
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
                System.out.println("Finished with Inner Thread");            
            }
        };
        // starting the thread, which will start execution of run method
        t.start();
    }
}

public class ThreadDemo {
    public static void main(String[] args) {
        //MyThread myThread = new MyThread();
        InnerThread it = new InnerThread("Inner Thread");
        for(int i = 0; i < 5; i++){
            System.out.println("Main thread" + i);
            try {
                Thread.sleep(5);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println("Finished with Main Thread");
    }

}

Here we are implementing the run method using an anonymous class. Note that Thread class is not explicitly extended here and the implementation of the run() method is provided when an instance of the thread is created.

If you want to do it using runnable interface run() method implementation it will only be a small change.

class InnerThread{
    Thread t;
    // Constructor
    public InnerThread(String name){
        // Anonymous class with run method implemented 
        // Using Runnable implementation
        Thread t = new Thread(new Runnable(){
            @Override
            public void run(){
                System.out.println("Entered run method " +Thread.currentThread().getName());
                for(int i = 0; i < 5; i++){
                    System.out.println(name + i);
                    try {
                        Thread.sleep(10);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                System.out.println("Finished with Inner Thread");            
            }
        }, name);// Name of the thread, second param
        // starting the thread, which will start execution of run method
        t.start();
    }
}

With Java 8 it is also possible to use lambda expression to provide implementation of the run method of the runnable interface. Runnable interface has a single abstract method run() thus it can be considered as a functional interface. Lambda expression can be used to provide implementation of that abstract method.

class LambdaThread{
    public LambdaThread(String name){
        // Lambda block - code inside the lambda block will
        // be the implementation of the run method. 
        Runnable r = () -> {
            System.out.println("Entered run method " +Thread.currentThread().getName());
            for(int i = 0; i < 5; i++){
                System.out.println("Lambda thread" + i);
                try {
                    Thread.sleep(10);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            System.out.println("Finished with Lambda Thread");
        };    
        //starting thread with the constructor of the thread class
        // that takes runnable instance and String as parameters
        new Thread(r, name).start();
    }
}

public class ThreadDemo {
    public static void main(String[] args) {
        LambdaThread lt = new LambdaThread("Lambda Thread");
        for(int i = 0; i < 5; i++){
            System.out.println("Main thread" + i);
            try {
                Thread.sleep(5);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println("Finished with Main Thread");
    }

}

Here we have used the lambda expression to provide implementation of the run method of the runnable interface. Lambda block provides the implementation of the run() method of the runnable interface. It is possible because runnable interface is a functional interface and provided target type for the lambda expression.

So these are the ways we can create thread in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. Difference between Thread and Process in Java
  2. Can we start the same thread twice in Java
  3. Thread states in Java multithreading
  4. What if run() method called directly instead of start() method
  5. Synchronization in Java multithreading
  6. Thread priorities in Java multithreading
  7. Java Multi-threading interview questions

You may also like -

No comments:

Post a Comment