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

Index Page : Link

Donate : Link

WordPress Blog : Link

              Runnable                           Runnable    
↑ ↑
Thread MyRunnable

MyThread
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()

Case 2 : t1.run()

Case 3 : t2.start()

Case 4 : t2.run()

Case 5 : r.start()

Case 6 : r.run()

Thread Class Constructors :

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store