Java — Defining a Thread by Extending Thread Class | Code Factory

Index Page : Link

Donate : Link

WordPress Blog : Link

package com.example.thread;public class ThreadTest {
public static void main(String... args) {
MyThread t = new MyThread(); // Thread instantiation
t.start(); // starting a Thread
// executed by Main Thread (line no. 8 to 10)
for(int i=0; i<5; i++) {
System.out.println("Main Thread");
}
}
}
// Define a Thread (line no. 15 to 22)
class MyThread extends Thread {
public void run() {
// job of Thread, executed by Child Thread (line no. 18 to 20)
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

Thread Schedular :

Difference between t.start() and t.run() :

Importance of Thread class start method :

start() {
1. Register this thread with thread schedular
2. Perform all other mandatory activities
3. Invoke run()
}

Overloading of run() method :

If we are not overriding run method :

Overriding of start() method :

Life Cycle of Thread :

IllegalThreadStateException :

Thread t = new Thread();
t.start();
.
.
.
t.start();