Java — Defining a Thread by Implementing Runnable Interface | Code Factory

Code Factory
2 min readMay 27, 2020

Index Page : Link

Donate : Link

WordPress Blog : Link

              Runnable                           Runnable    
↑ ↑
Thread MyRunnable

MyThread
  • Runnable interface present in java.lang package and it contain only one method run()
package com.example.thread;public class ThreadTest {
public static void main(String... args) {
MyRunnable r = new MyRunnable(); // Thread instantiation
Thread t = new Thread(r); // r = target Runnable
t.start(); // starting a Thread
// executed by Main Thread (line no. 9 to 11)
for(int i=0; i<5; i++) {
System.out.println("Main Thread");
}
}
}
// Define a Thread (line no. 16 to 23)
class MyRunnable implements Runnable {
public void run() {
// job of Thread, executed by Child Thread (line no. 19 to 21)
for(int i=0; i<5; i++) {
System.out.println("Child Thread");
}
}
}

Output :

Main Thread
Main Thread
Main Thread
Main Thread
Main Thread
Child Thread
Child Thread
Child Thread
Child Thread
Child Thread

Case Study :

MyRunnable r = new MyRunnable();
Thread t1 = new Thread();
Thread t2 = new Thread(r);

Case 1 : t1.start()

  • A new thread will be created which is responsible for the execution of Thread class run() method which has empty implementation

Case 2 : t1.run()

  • No new thread will be created and Thread class run() method will be executed just like a normal method call

Case 3 : t2.start()

  • A new thread will be created which is responsible for the execution of MyRunnable class run method

Case 4 : t2.run()

  • A new thread wouldn’t be created and MyRunnable run() method will be executed just like a normal method call

Case 5 : r.start()

  • We will get compile time error saying MyRunnable class doesn’t have start capability
  • CE : cannot find symbol
  • symbol : method start()
  • location : MyRunnable

Case 6 : r.run()

  • No new thread will be created and MyRunnable run() method will be executed like normal method call
  • Among 2 ways of defining a Thread implement runnable approach is recommended.
  • In the 1st approach our class always extends Thread class, there is no chance of extending any other class. Hence we are missing inheritance benefits.
  • But in the 2nd approach while implementing runnable interface we can extend any other class. Hence we wouldn’t missing any inheriance benefit.
  • Because of above reason implementing Runnable interface approach is recommended than extending Thread class.

Thread Class Constructors :

  1. Thread t = new Thread();
  2. Thread t = new Thread(Runnable r);
  3. Thread t = new Thread(String name);
  4. Thread t = new Thread(Runnable r, String name);
  5. Thread t = new Thread(ThreadGroup g, String name);
  6. Thread t = new Thread(ThreadGroup g, Runnable r);
  7. Thread t = new Thread(ThreadGroup g, Runnable r, String name);
  8. Thread t = new Thread(ThreadGroup g, Runnable r, String name, long stacksize);

--

--