How To Create A Thread In Java - Java Tutorial

How To Create A Thread In Java

BLUF: Mastering How To Create A Thread In Java is a key requirement for any Java developer. This lesson breaks down the object-oriented principles and syntax required to use this concept in real-world applications.
Write Once, Run Anywhere Tip: How To Create A Thread In Java

Java's versatility is unmatched. Learn how How To Create A Thread In Java fits into the Java ecosystem and improves your code structure in the tutorial below.

Multithreading is a core principle in Java development, enabling the simultaneous execution of multiple tasks within a program. Threads, which are smaller units of processing, operate within the framework of a larger process, optimizing resource consumption and improving the responsiveness of applications. This segment will delve into the creation of threads in Java, discussing different methodologies and recommended techniques.

In Java, threads can be created using either instances of the Thread class or by implementing the Runnable interface. The Thread class offers in-built features for handling multithreading, whereas the Runnable interface specifies a sole method, run, which holds the thread's executable code. Utilizing the Runnable interface allows for separating the task from the thread, enhancing code structure and facilitating reusability.

Two methods exist for creating a thread in Java:

  1. By extending the Thread class
  2. By implementing the Runnable interface
  3. Thread Class

One of the most straightforward methods to establish a thread in Java involves extending the Thread class and redefining its run method. The Thread class furnishes constructors and functions for generating and executing actions on a thread. Furthermore, the Thread class is an extension of the Object class and incorporates the Runnable interface.

Constructors of Thread Class

  • Thread
  • Thread(String name)
  • Thread(Runnable r)
  • Thread(Runnable r, String name)
  • Thread Class Methods

  • public void run: is used to perform action for a thread.
  • public void start: starts the execution of the thread.JVM calls the run method on the thread.
  • public void sleep(long miliseconds): Causes the currently executing thread to sleep (temporarily cease execution) for the specified number of milliseconds.
  • public void join: waits for a thread to die.
  • public void join(long miliseconds): waits for a thread to die for the specified miliseconds.
  • public int getPriority: returns the priority of the thread.
  • public int setPriority(int priority): changes the priority of the thread.
  • public String getName: returns the name of the thread.
  • public void setName(String name): changes the name of the thread.
  • public Thread currentThread: returns the reference of currently executing thread.
  • public int getId: returns the id of the thread.
  • public Thread.State getState: returns the state of the thread.
  • public boolean isAlive: tests if the thread is alive.
  • public void yield: causes the currently executing thread object to temporarily pause and allow other threads to execute.
  • public void suspend: is used to suspend the thread(depricated).
  • public void resume: is used to resume the suspended thread(depricated).
  • public void stop: is used to stop the thread(depricated).
  • public boolean isDaemon: tests if the thread is a daemon thread.
  • public void setDaemon(boolean b): marks the thread as daemon or user thread.
  • public void interrupt: interrupts the thread.
  • public boolean isInterrupted: tests if the thread has been interrupted.
  • public static boolean interrupted: tests if the current thread has been interrupted.
  • By Implementing Runnable Interface

An alternative method for generating threads in Java involves utilizing the Runnable interface. Any class that is meant to be run by a thread should implement the Runnable interface. This interface contains a single method called run. This technique is favored when there is a need to segregate the task from the thread, which helps in enhancing encapsulation and adaptability.

The run method is utilized to execute operations for a thread.

Starting a Thread

The start method of the Thread class is used to start a newly created thread. It performs the following tasks:

  • A new thread starts (with new callstack).
  • The thread moves from New state to the Runnable state.
  • When the thread gets a chance to execute, its target run method will run.
  • Thread Creation

1) Creating Thread by Extending Thread Class

File Name: Multi.java

Example

class Multi extends Thread{
public void run(){
System.out.println("thread is running...");
}
public static void main(String args[]){
Multi t1=new Multi();
t1.start();
 }
}

Output:

Output

thread is running...

In the following illustration, we create a personalized thread by extending the Thread class and replacing the run method with the specific functionality we require. Subsequently, we create an instance of the thread and invoke its start method to initiate its operation.

2) Java Thread Example by implementing Runnable interface

FileName: Multi3.java

Example

class Multi3 implements Runnable{
public void run(){
System.out.println("thread is running...");
}

public static void main(String args[]){
Multi3 m1=new Multi3();
Thread t1 =new Thread(m1);   // Using the constructor Thread(Runnable r)
t1.start();
 }
}

Output:

Output

thread is running...

Within this illustration, we establish a class named MyRunnable. This class implements the Runnable interface and encapsulates the task's logic within its run function. Subsequently, we instantiate a fresh Thread entity, providing a MyRunnable instance to its constructor. Finally, we initiate the thread's execution by invoking the start function.

If we do not inherit from the Thread class, the object of the class will not be considered a thread object. Therefore, it is necessary to manually instantiate the Thread class object. This involves passing an instance of our class that implements the Runnable interface, allowing the run method of the class to be executed.

3) Using the Thread Class: Thread(String Name)

The creation of new threads can be achieved by utilizing the constructors outlined in the Thread class.

FileName: MyThread1.java

Example

public class MyThread1
{
// Main method
public static void main(String argvs[])
{
// creating an object of the Thread class using the constructor Thread(String name) 
Thread t= new Thread("My first thread");

// the start() method moves the thread to the active state
t.start();
// getting the thread name by invoking the getName() method
String str = t.getName();
System.out.println(str);
}
}

Output:

Output

My first thread

4) Using the Thread Class: Thread(Runnable r, String name)

Observe the following program.

FileName: MyThread2.java

Example

public class MyThread2 implements Runnable
{  
public void run()
{  
System.out.println("Now the thread is running ...");  
}  
  
// main method
public static void main(String argvs[])
{ 
// creating an object of the class MyThread2
Runnable r1 = new MyThread2(); 

// creating an object of the class Thread using Thread(Runnable r, String name)
Thread th1 = new Thread(r1, "My new thread");  

// the start() method moves the thread to the active state
th1.start(); 

// getting the thread name by invoking the getName() method
String str = th1.getName();
System.out.println(str);
}  
}

Output:

Output

My new thread
Now the thread is running ...

Create a thread in Java MCQ

  1. Which of the following is a correct way to create a thread in Java?
  • Implementing the Runnable interface
  • Extending the Thread class
  • Both a and b
  • Neither a nor b

Explanation: In Java, we can create a thread either by implementing the Runnable interface or by extending the Thread class.

  1. What method must be overridden when implementing the Runnable interface?
  • start
  • run
  • init
  • execute

Explanation: When implementing the Runnable interface, the run method must be overridden to define the code that constitutes the new thread's task.

  1. What is the correct sequence to start a thread using the Runnable interface?
  • Create an instance of Thread class and call start
  • Call run method directly
  • Create an instance of Runnable class and call start
  • Create an instance of Thread class and call run

Explanation: To start a thread using the Runnable interface, you need to create an instance of the Thread class, passing the Runnable object to its constructor, and then call the start method.

  1. What is the state of a thread when the start method is called?
  • Runnable
  • Running
  • Waiting

Explanation: When the start method is called on a thread, it moves from the New state to the Runnable state, making it eligible to be run by the thread scheduler.

  1. How can we create a daemon thread in Java?
  • By calling setDaemon(true) method on a thread object
  • By overriding the run method
  • By extending the Thread class
  • By implementing the Runnable interface

A Java daemon thread is established by invoking the setDaemon(true) function on a thread instance prior to initiating it.

Input Required

This code uses input(). Please provide values below:

Logic Practice
Install Logic Practice
Add to home screen for a faster app-like experience