Thread in Java Explained [Simple Examples]


JAVA

Author: Bashir Alam
Reviewer: Deepak Prasad

 

Introduction to the thread in Java

A thread in java, is the path followed when executing a program. A single-threaded application has only one thread and can handle only one task at a time. To handle multiple tasks in parallel, multi-threading is used. For example, multiple threads are created and each performs a different task. In this tutorial, we will learn about the thread in java. We will learn how to create and start a thread.

We will also cover the implementation of a runnable interface in java and will see how we can start a thread using the runnable interface. At the same time, we will also take various examples of the thread in java and will solve different problems. Moreover, we will also cover multi-threads in java and will create some multi-threads using java in a couple of ways. All in all, this tutorial will contain all the necessary information that you need to know in order to get started with thread in java.

 

Getting started with the thread in Java

A thread in java is like a virtual CPU that can execute Java code. We already know that when a Java application is started its main() method is executed by the java main thread which is a special thread that is created by the Java VM to run the application. In this section, we will create and start the thread by taking the examples.

 

Syntax to Create and start the thread in Java

We already discuss and defined the thread in Java. Let us now see how we can create a thread in a java programming language. The basic syntax of creating a java thread looks like this.

Thread thread = new Thread();

And we can start the newly created thread using the following syntax.

thread.start();

Basically, there are two different ways to run the thread in the Java programming language.

  • Extend the Thread class and then creating a new subclass and
  • Create a new thread using the runnable interface

which we will discuss in the next section.

 

Method-1: Java Thread Example by Extending Thread class

Now we already know how to start and create and new thread, let us take an example and create a thread by extending the Thread class. See the example below which extends the thread class and then prints the message.

// Extending Thread class and creating child class
public class Main extends Thread {
  // java main method
  public static void main(String[] args) {
    // creating new thread inside the main method
    Main thread = new Main();
    // starting the thread
    thread.start();
    // printing
    System.out.println("The thread inside the main method!!!");
  }
  // method to run the thread message
  public void run() {
    // printing 
    System.out.println("The thread outside the main method!!");
  }
}

Output:

The thread inside the main method!!!
The thread outside the main method!!

Notice that in our main method, we did not call the run function but still it run successfully because of the java thread.

 

Method-2: Implementation of the runnable interface in Java

The second way to specify and run a thread in java is to use the runnable interface in java which is in the java.lang.Runnable interface. A Java object that implements the runnable interface can be executed by a Java thread. In this section, we will learn how we can run a thread in java using the runnable interface.

 

Syntax to use the runnable interface in Java class

The first way to implement the Java runnable interface is by creating our own Java class that implements the runnable interface. Here is the simple syntax of a custom Java class that implements the runnable interface. See the example below:

// main class implementing the runnable interface
public class Main implements Runnable {
  // run method
  public void run(){
    // statements of run method
  }
}

The statements inside the run method will be executed because we are implementing the runnable interface.

 

Example: Create Java thread using runnable interface

Now let us take an example of a thread in java using the runnable interface and let start the thread. See the example below:

// java main class implements runnable
public class Main implements Runnable {
  // java main method
  public static void main(String[] args) {
      // creating mew runnable
      Runnable runnable = new Main();
      // creating new Java thread
      Thread thread = new Thread(runnable);
      // thread started
      thread.start();
  }
  // run method
  public void run() {
      // printing the statement
      System.out.println("Welcome to golinuxcloud!");
  }
}

Output:

Welcome to golinuxcloud!

 

Anonymous implementation of the runnable interface in Java

Another way to implement the runnable interface in java is anonymous implementation.

 

Syntax of anonymous Java class

Here is the simple syntax of an anonymous Java class that implements the runnable interface. See the example below:

public static void main(String[] args) {
  // creating runnable interface
  Runnable Main = new Runnable(){
    // run method
    public void run(){
        // statements
    }
  // semi colon to show the ending of runnable block
  };
}

In the above syntax notice that there is a semicolon after the ending of the runnable block, this is to show that the runnable blocks end here. If we will not put the semi-colon there, we will get a syntax error.

 

Example-1 Thread in Java using an anonymous implementation of the runnable interface

Now we are familiar with the syntax of anonymous implementation of the runnable interface in java. Let us now take an example of a thread in java and start the thread using the anonymous implementation of the runnable interface. See the example below:

// Java main class
class Main{
// Java main method
public static void main(String... ar){
  //Creating an object of Anonymous class which extends Thread class.
  Thread thread= new Thread(){ 
    //Anonymous class overriding run() method of Thread class	
    public void run()	{
      System.out.println("Welcome to the golinuxcloud!");
     }
    }; // the run block ends here!
  
    // the start of thread
   thread.start();
  }
}

Output:

Welcome to the golinuxcloud!

Notice that we were able to run successfully the block of code inside our run method by starting the thread.

 

Multithreading in Java programming language

Multithreading in java refers to a process of executing two or more threads simultaneously for maximum utilization of the CPU. One more term that we will use with the multithreading is the ID of the thread which is a positive long number generated when the thread is created. The thread ID is unique and remains unchanged during its lifetime. When a thread is terminated, this thread ID may be reused. We will use the IDs of multi-threads to confirm that we have more than one thread. We already had discussed two different ways of starting a thread in java. In this section, we will use the same two methods to starting multithreading in Java as well.

 

Multi-thread creation by extending the Thread class

The getId()method of the Thread class in java returns the identifier of the invoked thread. We will use this method to get the id of threads. Now let us take an example and see how we can generate multi-threads by extending the thread class. See the example below:

// creating java thread class which extends the Thread clas
class thread extends Thread {
  // run method
  public void run()
  {
    // Displaying the thread that is running by its id
    System.out.println("The ID of current thread is : " + Thread.currentThread().getId());
  }
}

// Java Main Class
public class Main {
  // java main method
  public static void main(String[] args){
      // creating variable for thread numbers
      int num = 5; 
      // for loop
      for (int i = 0; i < num; i++) {
          // creating new thread 
          thread object= new thread();
          // starting 
          object.start();
      }
  }
}

Output:

The ID of current thread is : 12
The ID of current thread is : 15
The ID of current thread is : 16
The ID of current thread is : 14
The ID of current thread is : 13

Notice that we get different IDs, which means that multiple threads are working in our program.

 

Implementing multi-threads using a runnable interface

Now let us create multi-threads using the runnable interface. We already had learned how we can create a thread in java using the implementation of the runnable interface. See the example below, which creates multiple threads using the runnable interface method.

// creating runnable class
class runnable implements Runnable {
       // run method
	public void run()	{
		// Displaying the thread that is running
		System.out.println("The ID of current running thread is: " + Thread.currentThread().getId());
	}
}
// Main Class
class Main {
        // java main method
	public static void main(String[] args){
               // creating variable for threads number
		int num = 5;
		for (int i = 0; i < num; i++) {
                        // creating new thread object
			Thread object= new Thread(new runnable());
                        // starting
			object.start();
		}
	}
}

Output:

The ID of current running thread is: 12
The ID of current running thread is: 16
The ID of current running thread is: 15
The ID of current running thread is: 14
The ID of current running thread is: 13

Notice that we get a different ID for each of the five threads that we had created using the java for loop. You can learn more about the for loop from the article the Java for loop.

 

Summary

A thread is a single sequential flow of control within a program. As a sequential flow of control, a thread must carve out some of its own resources within a running program. There can be multi-threads in a java program as well. In this tutorial, we learned about the thread in Java. We learned about the two most popular ways of creating the thread in java along with various examples. Moreover, we also discussed how to create multi-threads in java using various ways. In a nutshell, this tutorial contains all the necessary information and examples that are useful in order to start working with the thread in java.

 

Further Reading

Thread in java
Multiple threads in java
More about java thread

 

Bashir Alam

Bashir Alam

He is a Computer Science graduate from the University of Central Asia, currently employed as a full-time Machine Learning Engineer at uExel. His expertise lies in Python, Java, Machine Learning, OCR, text extraction, data preprocessing, and predictive models. You can connect with him on his LinkedIn profile.

Can't find what you're searching for? Let us assist you.

Enter your query below, and we'll provide instant results tailored to your needs.

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

Buy GoLinuxCloud a Coffee

For any other feedbacks or questions you can send mail to admin@golinuxcloud.com

Thank You for your support!!

Leave a Comment