Java Creating Thread

In the last chapter we have already seen the different states of the thread. In this chapter we will be learning the creation of thread

Two ways to create a thread :

  1. Extending the Thread class
  2. Implementing the Runnable interface

Way 1 : Extending the Thread class

Firstly consider the following example -

package com.c4learn.thread;
public class ThreadExample extends Thread {
     public void run() {
         System.out.println("Thread is running !!");
     }
     public static void main(String[] args) {
         ThreadExample t1 = new ThreadExample();
         t1.start();
     }
}

output :

Thread is running !!

Explanation of code :

  1. ThreadExample class extends the Thread class and overrides its run method.
  2. ThreadExample class begins by instantiating itself.
  3. A newly created Thread will be in the born state or new state, then by calling the start() method thread moves from new state to runnable state
  4. start() method will call run() method which is overriden by the ThreadExample class.

Some conclusions :

Now we can frame some conclusions from the program written above -

  1. We need to override run() method of thread class.
  2. Code written inside run() method is executed when we call start() method of class which extends Thread class.
  3. If run() method returns or throws an exception then we can say that thread dies

Way 2 : Implementing Runnable interface

Consider the following example -

package com.c4learn.thread;
public class RunnableThread implements Runnable {
    public void run() {
         for (int i = 1; i <= 10; i++) {
             System.out.println(i);             
         }
     }
     public static void main(String[] args) {
    	 RunnableThread t1 = new RunnableThread();
          Thread thread = new Thread(t1);
          thread.start();
     }
}

output :

1
2
3
4
5
6
7
8
9
10

Explanation :

In the above program, firstly class needs to implement the runnable interface.

public class RunnableThread implements Runnable {}

Runnable interface have run() method which we need to implement.

public void run() {
    for (int i = 1; i <= 10; i++) {
        System.out.println(i);             
    }
}

Now we need to create an object of the class which implements the runnable interface.

RunnableThread t1 = new RunnableThread();

If we use Runnable then we have to instantiate the Thread class and pass the Runnable to it.

Thread thread = new Thread(t1);

After creating the thread object we can invoke the start() method to execute the run() method.