Curriculum
Course: Learn Java Programming
Login

Curriculum

Learn Java Programming

Video lesson

Creating a Thread By Extending a Thread Class in Java

In this lesson, you will learn.

  • Creating a Thread
  • Example
  • Creating Multiple Threads
  • Example

 

Creating A Thread

There are two primary ways to create a thread in Java:

In this lesson, you will learn about Creating threads by extending The Thread Class.

 

Creating A Thread By Extending The Thread Class

 

 

Creating a new thread by extending a Thread class includes the following 3 steps.

 

Step 1: Define a Class that Extends Thread

Start by defining a new class that extends the built-in Java Thread class.

By extending a Thread, your class inherits all the methods of the Thread class, which are essential for managing the thread’s lifecycle.

class MyThread extends Thread {
    // Class body
}

 

Step 2: Override the run() Method

The run() method contains the entire body of the Thread. It is considered the heart and soul of a Thread.

The run( ) method is the entry point for another concurrent thread of execution within your program.

class MyThread extends Thread {
    @Override
    public void run() {
        // Code that the thread will execute
        System.out.println("Thread is running");
    }
}

 

Step 3: Create an Instance of Your Thread Class and Start the Thread

Once you have defined your thread class and overridden the run() method, create an instance of this class in your application. This instance represents your new thread.

To start the thread, call the start() method on the instance of your thread class. This method is inherited from the Thread class and is used to initiate the execution of the run() method in the new thread.

public class ThreadExample {
    public static void main(String[] args) {
        MyThread myThread = new MyThread(); // Creating the thread Instance
        myThread.start(); // Starting the thread
    }
}

 

Example: Creating a Thread by Extending a Thread Class

In the following example, we are creating a user thread named ThreadingDemo by extending a Thread class and then creating an instance of that class.

The extending class must override the run( ) method, which is the entry point for the new thread. It must also call the start( ) method to begin the execution of the new thread.

package creatingthreads;
//Step-1
class ThreadingDemo extends Thread {
	private int threadNumber;

	public ThreadingDemo(int threadNumber) {
		this.threadNumber = threadNumber;
	}
	
    //Step-2
	@Override
	public void run() {
		for (int i = 1; i <= 10; i++) {
			try {
				sleep(500);
				System.out.println("Thread No "+threadNumber 
						+": iteration "+i+" is running.");
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}	
		}	
		System.out.println("Exiting child thread: "+threadNumber);
	}	
}
public class MultiThreadingMain {
	public static void main(String args[]) {
        //Step-3
		ThreadingDemo t1 = new ThreadingDemo(1); //Creating a new Thread
		t1.start();
		System.out.println("Exiting Main thread.");
	}
}

Output

Exiting Main thread.
Thread No 1: iteration 1 is running.
Thread No 1: iteration 2 is running.
Thread No 1: iteration 3 is running.
Thread No 1: iteration 4 is running.
Thread No 1: iteration 5 is running.
Thread No 1: iteration 6 is running.
Thread No 1: iteration 7 is running.
Thread No 1: iteration 8 is running.
Thread No 1: iteration 9 is running.
Thread No 1: iteration 10 is running.
Exiting child thread: 1

 

Explanation

In the above program, the main thread exits first and the child thread continues its execution and sleeps for 500 milliseconds.

If you want to ensure that the main thread must be the last thread to finish running, you can add a sleep time inside a main thread as shown in the below code snippet.

public class MultiThreadingMain {
	public static void main(String args[]) {
		ThreadingDemo t1 = new ThreadingDemo(1); //Creating a new Thread
		t1.start();
		try {
			for(int i = 10; i > 0; i--) {
				System.out.println("Main Thread: " +"iteration "
			+i+" is running.");
				Thread.sleep(1000);
			}
		} catch (InterruptedException e) {
			System.out.println("Main thread interrupted.");
		}
		System.out.println("Exiting Main thread.");
	}
}

Output

Main Thread: iteration 10 is running.
Thread No 1: iteration 1 is running.
Main Thread: iteration 9 is running.
Thread No 1: iteration 2 is running.
Thread No 1: iteration 3 is running.
Main Thread: iteration 8 is running.
Thread No 1: iteration 4 is running.
Thread No 1: iteration 5 is running.
Main Thread: iteration 7 is running.
Thread No 1: iteration 6 is running.
Thread No 1: iteration 7 is running.
Main Thread: iteration 6 is running.
Thread No 1: iteration 8 is running.
Thread No 1: iteration 9 is running.
Main Thread: iteration 5 is running.
Thread No 1: iteration 10 is running.
Exiting child thread: 1
Main Thread: iteration 4 is running.
Main Thread: iteration 3 is running.
Main Thread: iteration 2 is running.
Main Thread: iteration 1 is running.
Exiting Main thread.

 

Question

Can a Main thread exit first before a child thread in Java? if yes, what is the impact of it?

Answer: Yes, in Java, the main thread can exit before a child thread (or any other thread that it spawns).

Impact of Main Thread Exiting First

1. Program Continuation:

If the child thread is a user thread (as in the example above), the JVM will continue to run until this child thread completes its execution, even though the main thread has already finished.

This is because the JVM waits for all user threads to finish before it shuts down.

2. No Direct Impact on Other Threads:

The main thread exiting does not directly affect the execution of child threads unless those child threads are specifically depending on the main thread for some resources or synchronization (like signals or shared data).

3. Daemon Threads:

If the child threads were daemon threads, the JVM would exit as soon as the main thread and any other user threads (if any) were complete, potentially leaving daemon threads in an incomplete state.

This would mean that tasks being performed by daemon threads could be abruptly stopped.

A daemon thread is a low-priority thread that runs in the background to perform tasks such as garbage collection, housekeeping operations, or to provide services to user threads (non-daemon threads).

To make a thread a daemon thread in Java, you must call the setDaemon(true) method on the Thread object before the thread is started.

4. Resource Management and Cleanup

If the main thread holds critical resources or performs important cleanup tasks, exiting it prematurely without ensuring that these responsibilities are properly delegated or handled can lead to resource leaks or improper application state.

 

Creating Multiple Threads

So far, you have been using only two threads: the main thread and one child thread.

Your program can spawn many threads. The following program creates three child threads.

 

 

Example: Creating Multiple Threads

package creatingmultiplethreads;

class ThreadingDemo extends Thread {
	private int threadNumber;

	public ThreadingDemo(int threadNumber) {
		this.threadNumber = threadNumber;
	}

	@Override
	public void run() {
		for (int i = 1; i <= 5; i++) {
			try {
				sleep(500);
				System.out.println("Thread No "+threadNumber 
						+": iteration "+i+" is running.");
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}	
		}	
		System.out.println("Exiting child thread: "+threadNumber);
	}	
}
public class CreatingMultipleThread {

	public static void main(String[] args) {
		//Creating 3 threads
		ThreadingDemo t1 = new ThreadingDemo(1); //Creating a new Thread
		ThreadingDemo t2 = new ThreadingDemo(2); //Creating a new Thread
		ThreadingDemo t3 = new ThreadingDemo(3); //Creating a new Thread
		t1.start();
		t2.start();
		t3.start();
		try {
			for(int i = 5; i > 0; i--) {
				System.out.println("Main Thread: " +"iteration "
			+i+" is running.");
				Thread.sleep(1000);
			}
		} catch (InterruptedException e) {
			System.out.println("Main thread interrupted.");
		}
		System.out.println("Exiting Main thread.");
	}
}

 

Output: First Run

Main Thread: iteration 5 is running.
Thread No 2: iteration 1 is running.
Thread No 3: iteration 1 is running.
Thread No 1: iteration 1 is running.
Main Thread: iteration 4 is running.
Thread No 2: iteration 2 is running.
Thread No 3: iteration 2 is running.
Thread No 1: iteration 2 is running.
Thread No 1: iteration 3 is running.
Thread No 3: iteration 3 is running.
Thread No 2: iteration 3 is running.
Main Thread: iteration 3 is running.
Thread No 3: iteration 4 is running.
Thread No 2: iteration 4 is running.
Thread No 1: iteration 4 is running.
Thread No 1: iteration 5 is running.
Thread No 2: iteration 5 is running.
Exiting child thread: 1
Thread No 3: iteration 5 is running.
Exiting child thread: 2
Exiting child thread: 3
Main Thread: iteration 2 is running.
Main Thread: iteration 1 is running.
Exiting Main thread.

 

Output: Second Run

Main Thread: iteration 5 is running.
Thread No 1: iteration 1 is running.
Thread No 3: iteration 1 is running.
Thread No 2: iteration 1 is running.
Thread No 3: iteration 2 is running.
Main Thread: iteration 4 is running.
Thread No 1: iteration 2 is running.
Thread No 2: iteration 2 is running.
Thread No 3: iteration 3 is running.
Thread No 2: iteration 3 is running.
Thread No 1: iteration 3 is running.
Main Thread: iteration 3 is running.
Thread No 1: iteration 4 is running.
Thread No 2: iteration 4 is running.
Thread No 3: iteration 4 is running.
Thread No 1: iteration 5 is running.
Thread No 2: iteration 5 is running.
Thread No 3: iteration 5 is running.
Exiting child thread: 3
Exiting child thread: 1
Exiting child thread: 2
Main Thread: iteration 2 is running.
Main Thread: iteration 1 is running.
Exiting Main thread.

 

Explanation

For each run, you will get a different output. This is due to the concurrent running of multiple threads and all three child threads share the CPU.

Notice the call to sleep(1000) in main( ). This causes the main thread to sleep for 1 second and ensures that it will finish last.

 

 

 


End of the lesson….enjoy learning

 

 

Student Ratings and Reviews

 

 

 

There are no reviews yet. Be the first one to write one.

 

 

Submit a Review