Multithreading - Creating your own thread

Java provides different ways of creating threads as follows :
1. Extending Thread Class

We can extend the Thread class for creating our own custom Thread class and override its run() method as follows :

public class MyThreadExtendingThreadClass extends Thread {
    @Override    public void run() {
        for(int i=0; i<100; i++) {
            System.out.println("Child Thread by extending Thread : " + i);        }
    }
}

Then in the main class, you can create a object of this class and call the start() method of the thread :

MyThreadExtendingThreadClass myThreadExtendingThreadClass = new MyThreadExtendingThreadClass();myThreadExtendingThreadClass.start();

When you call the start() method, it internally calls the run() method and creates a separate path of execution in the program.

If you try to call the start() method multiple times, it will throw IllegalThreadStateException.

What if you directly call run() instead of start(), in that case a new thread will not be created and your program will work as a single-threaded program only.

2. Implementing Runnable interface

We can implement Runnable interface to create our own custom Thread class as follows :

public class MyThreadImplementingRunnableInterface implements Runnable {
    public void run() {
        for(int i=0; i<100; i++) {
            System.out.println("Child thread by implemented interface : " + i);        }
    }
}

Then in the main class, we can create a Thread object by passing the instance of custom class, that implements Runnable. And then call the thread's start() method.

MyThreadImplementingRunnableInterface myThreadImplementingRunnableInterface = new MyThreadImplementingRunnableInterface();Thread thread = new Thread(myThreadImplementingRunnableInterface);thread.start();

Note: Runnable has only one method run(), it doesnt have a start method. When we create a thread and pass runnable, the newly created thread object's start() points to the run() method of the runnable object.

An example for the above codes can be found here

Lastly, why Java provides two different ways to create threads and which approach should you use?  Classes should be extended only when you want to enhance the behaviour of a class. Secondly, by implementing the Runnable interface, you give the class an opportunity to extend a different class.

Comments

Popular posts from this blog

Collection Framework - HashSet And LinkedHashSet class

Collection Framework - Cursors in Java

Hashed data structures