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

              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");
}
}
}
Main Thread
Main Thread
Main Thread
Main Thread
Main Thread
Child Thread
Child Thread
Child Thread
Child Thread
Child Thread
MyRunnable r = new MyRunnable();
Thread t1 = new Thread();
Thread t2 = new Thread(r);

--

--

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