Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Java Threads
3.
Thread class
3.1.
Methods used in Thread class
4.
Runnable Interface
4.1.
Runnable Interface Implementation
5.
Advantages of Creating Threads
6.
Examples
6.1.
Code 1
6.2.
Code 2
7.
FAQs
8.
Key Takeaways
Last Updated: Mar 27, 2024

Creating a Thread

Crack Google SDE interview : Essential projects
Speaker
Saurav Prateek
SDE-2 @
20 Jun, 2024 @ 01:30 PM

Introduction

A Java Thread is the same as a virtual CPU that helps code execution. The main Thread executes its main() method when a Java application is started. You can also create and start more threads to implement parts of your application code in parallel with the main Thread.

Java Threads

Threads can be referred to as the lightweight process. They used less memory usage to create and exit the function. The main Thread is what makes the entire program. The secondary Thread is an outcome of the main Thread. 

A thread can be created by:

  • Implementing the Java.lang.Runnable interface.
  • Extending the Java.lang.Thread class.
Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Thread class

Thread class gives the constructors and methods to create and perform several operations on a thread. Thread class extends the Object class and implements via Runnable interface.

Methods used in Thread class

  • public void run(): This method acts on a thread.
Thread my_thread = new Thread(MyRunnable());
my_thread.run();

 

  • public void start(): This starts the execution of the Thread.JVM and calls the run() method.
Thread t1 = new Thread();
t1.start();

 

  • public void sleep(long millisec): This method causes the current Thread to sleep with a specified time passed in the parameter.
Thread t = new thread();
t.sleep(10L*1000);

 

  • public String getName(): This Thread will return the name of the current Thread.
Thread t = new Thread(“My thread”);
String str = t.getName();

 

  • public void join(long millisec): This method waits for the Thread to die for the time specified in the parameter.
Thread the = new Thread();
the.join(100);

 

  • public void yield(): This Thread allows us to pause the current Thread and allows other threads to execute.
Thread tr = new Thread();
tr.yield();

 

  • public void stop(): This method will stop the Thread.
Thread tr = new Thread();
tr.stop();

Runnable Interface

The second method mentions what type of code a thread should execute by creating a class that implements the Java.lang.Runnable interface. A Java Thread class can perform an object that implements this Runnable interface. The Runnable interface is a standard Java Interface that helps execute the Runnable interface that a Java Thread can achieve.

Runnable Interface Implementation

The best way to create the Java Runnable interface is by creating your own Java class that implements the Runnable interface. 

public class ExampleRunnable implements Runnable {
	public void run(){
	System.out. println("My Runnable");
	}
}

Advantages of Creating Threads

  • These threads are more lightweight, which means they take less time and resources to create a thread.
  • They help in sharing the data of their parent process.
  • When Thread communicates, it's much simpler than process communication.
  • Switching between threads is much cheaper than between processes.

Examples

Code 1

public class Thread1 extends Thread {

	public void run()
    {
        System.out.print("Welcome to Coding Ninjas.");
    }
    public static void main(String[] args)
    {
        Thread1 g = new Thread1(); 
        g.start();
    }
}

Output

Welcome to Coding Ninjas.


In this example, we have developed a thread, and we have called an in-built function start to start the Thread.

Try it on online java compiler.

Code 2

public class Thread2 implements Runnable {

	    public static void main(String args[])
	    {
	       Thread2 cn = new Thread2();
	  
	       Thread t = new Thread(cn, "CN");
	  
	       t.start();
	  
	       System.out.println(t.getName());
	    }
	    @Override public void run()
	    {
	        System.out.println("Inside blog");
	    }
	}

Output

CN
Inside blog

In this example, we have used one of the states of the threads, i.e., Runnable. We have created a Thread object and passed another object of the class. Then we have used the in-built method start() to start the Thread. Then we have used Override to implement the parent class.

Also see, Duck Number in Java and Hashcode Method in Java

FAQs

  1. How to create a thread in Java?
    A thread can be created by implementing the Runnable interface and overriding the run() method. A thread object is required to make a start() method. The Main Thread is required to initiate the program execution.
     
  2. How to run a code in a thread?
    There are several methods to specify which code to run in that Thread. These are Implement the interface java.lang.Runnable and pass the instance of the class implementing it to the Thread constructor.

Key Takeaways

This article has covered how to create a thread in Java. We also gave a brief introduction about creating a Thread in Java. We also discussed the Java Threads and Thread class and various methods in Thread class with their syntax. We also discussed the Runnable interface and its implementation. We also discussed the advantages of a Thread class. We also discussed a few examples of creating Threads in Java.

If you want to practice this concept, please visit our website Code Studio Library.

Previous article
Life Cycle Of A Thread
Next article
Thread scheduler
Live masterclass