Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Java Arrays
  • Java Strings
  • Java OOPs
  • Java Collection
  • Java 8 Tutorial
  • Java Multithreading
  • Java Exception Handling
  • Java Programs
  • Java Project
  • Java Collections Interview
  • Java Interview Questions
  • Java MCQs
  • Spring
  • Spring MVC
  • Spring Boot
  • Hibernate
Open In App
Next Article:
What does start() function do in multithreading in Java?
Next article icon

Java Thread Class

Last Updated : 10 Jan, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Thread is a line of execution within a program. Each program can have multiple associated threads. Each thread has a priority which is used by the thread scheduler to determine which thread must run first. Java provides a thread class that has various method calls to manage the behavior of threads by providing constructors and methods to perform operations on threads. 

A Thread is a program that starts with a method() frequently used in this class only known as the start() method. This method looks out for the run() method which is also a method of this class and begins executing the body of the run() method. Here, keep an eye on the sleep() method which will be discussed later below.

Note: Every class that is used as a thread must implement Runnable interface and override its run method.

Syntax

public class Thread extends Object implements Runnable

Constructors of Thread Class

Constructor Action Performed 
Thread()Allocates a new Thread object.
Thread(Runnable target)Allocates a new Thread object.
Thread(Runnable target, String name)Allocates a new Thread object.
Thread(String name)Allocates a new Thread object.
Thread(ThreadGroup group, Runnable target)Allocates a new Thread object.
Thread(ThreadGroup group, Runnable target, String name)Allocates a new Thread object so that it has targeted as its run object, has the specified name as its name, and belongs to the thread group referred to by a group.
Thread(ThreadGroup group, Runnable target, String name, long stackSize)Allocates a new Thread object so that it has targeted as its run object, has the specified name as its name, and belongs to the thread group referred to by group, and has the specified stack size.
Thread(ThreadGroup group, String name)Allocates a new Thread object.

Example: Java program to demonstrate usage of Thread class 

Java
// Java Program to demonstrate // usage of Thread class  class MyThread extends Thread  {   	// Overriding the run method   	@Override     public void run()      {         for (int i = 0; i < 5; i++)          {             System.out.println(Thread.currentThread().getName()                                + " - Count : " + i);                        	try {               	// Sleep for 500 milliseconds                 Thread.sleep(500);              }            	catch (InterruptedException e) {                 System.out.println("Thread interrupted");             }         }     } }  // Main Class public class Geeks  {     public static void main(String[] args)      {         MyThread thread1 = new MyThread();         MyThread thread2 = new MyThread();          thread1.setName("Thread 1");         thread2.setName("Thread 2");        	// Start thread 1         thread1.start();               	// Start thread 2         thread2.start();      } } 

Output:

Thread 1 - Count : 0
Thread 2 - Count : 0
Thread 1 - Count : 1
Thread 2 - Count : 1
Thread 1 - Count : 2
Thread 2 - Count : 2
Thread 1 - Count : 3
Thread 2 - Count : 3
Thread 2 - Count : 4
Thread 1 - Count : 4

Note: Execution of the thread is not according to the sequence, it can be executed in any sequence Thread 1 then Thread 2 , or Thread 2 then Thread 1.

Methods of Thread Class

MethodsAction Performed 
activeCount()Returns an estimate of the number of active threads in the current thread's thread group and its subgroups
checkAccess()Determines if the currently running thread has permission to modify this thread
clone()Throws CloneNotSupportedException as a Thread can not be meaningfully cloned
currentThread()Returns a reference to the currently executing thread object
dumpStack()Prints a stack trace of the current thread to the standard error stream
enumerate(Thread[] tarray)Copies into the specified array every active thread in the current thread's thread group and its subgroups
getAllStackTraces()Returns a map of stack traces for all live threads
getContextClassLoader()Returns the context ClassLoader for this Thread
getDefaultUncaughtExceptionHandler()Returns the default handler invoked when a thread abruptly terminates due to an uncaught exception
getId()Returns the identifier of this Thread
getName()Returns this thread's name
getPriority()Returns this thread's priority
getStackTrace()Returns an array of stack trace elements representing the stack dump of this thread
getState()Returns the state of this thread
getThreadGroup()Returns the thread group to which this thread belongs
getUncaughtExceptionHandler()Returns the handler invoked when this thread abruptly terminates due to an uncaught exception
holdsLock(Object obj)Returns true if and only if the current thread holds the monitor lock on the specified object
interrupt()Interrupts this thread
interrupted()Tests whether the current thread has been interrupted
isAlive()Tests if this thread is alive
isDaemon()Tests if this thread is a daemon thread
isInterrupted()Tests whether this thread has been interrupted
join()Waits for this thread to die
join(long millis)Waits at most millis milliseconds for this thread to die
run()If this thread was constructed using a separate Runnable run object, then that Runnable object's run method is called; otherwise, this method does nothing and returns
setContextClassLoader(ClassLoader cl)Sets the context ClassLoader for this Thread
setDaemon(boolean on)Marks this thread as either a daemon thread or a user thread
setDefaultUncaughtExceptionHandler( Thread.UncaughtExceptionHandler eh)Set the default handler invoked when a thread abruptly terminates due to an uncaught exception, and no other handler has been defined for that thread
setName(String name)Changes the name of this thread to be equal to the argument name.
setUncaughtExceptionHandler( Thread.UncaughtExceptionHandler eh)Set the handler invoked when this thread abruptly terminates due to an uncaught exception
setPriority(int newPriority)Changes the priority of this thread
sleep(long millis)Causes the currently executing thread to sleep (temporarily cease execution) for the specified number of milliseconds, subject to the precision and accuracy of system timers and schedulers
start()Causes this thread to begin execution; the Java Virtual Machine calls the run method of this thread
toString()Returns a string representation of this thread, including the thread's name, priority, and thread group
yield()A hint to the scheduler that the current thread is willing to yield its current use of a processor

Methods Inherited from java. lang.Object Class 

  • equals()
  • finalize()
  • getClass()
  • hashCode()
  • notify()
  • notifyAll()
  • toString()
  • wait()

Next Article
What does start() function do in multithreading in Java?

M

Mayank Kumar
Improve
Article Tags :
  • Java
  • Java-Multithreading
  • Java-lang package
Practice Tags :
  • Java

Similar Reads

    Multithreading in Java
    Multithreading is a Java feature that allows the concurrent execution of two or more parts of a program for maximum utilization of the CPU. Each part of such a program is called a thread. So, threads are lightweight processes within a process.Different Ways to Create ThreadsThreads can be created by
    3 min read
    Lifecycle and States of a Thread in Java
    A thread in Java can exist in any one of the following states at any given time. A thread lies only in one of the shown states at any instant:New StateRunnable StateBlocked StateWaiting StateTimed Waiting StateTerminated StateThe diagram below represents various states of a thread at any instant:Lif
    5 min read
    Main thread in Java
    Java provides built-in support for multithreaded programming. A multi-threaded program contains two or more parts that can run concurrently. Each part of such a program is called a thread, and each thread defines a separate path of execution.When a Java program starts up, one thread begins running i
    4 min read
    Java Concurrency - yield(), sleep() and join() Methods
    In this article, we will learn what is yield(), join(), and sleep() methods in Java and what is the basic difference between these three. First, we will see the basic introduction of all these three methods, and then we compare these three. We can prevent the execution of a thread by using one of th
    5 min read
    Inter-thread Communication in Java
    Inter-thread communication in Java is a mechanism in which a thread is paused from running in its critical section, and another thread is allowed to enter (or lock) the same critical section to be executed.Note: Inter-thread communication is also known as Cooperation in Java.What is Polling, and Wha
    6 min read
    Java Thread Class
    Thread is a line of execution within a program. Each program can have multiple associated threads. Each thread has a priority which is used by the thread scheduler to determine which thread must run first. Java provides a thread class that has various method calls to manage the behavior of threads b
    5 min read
    What does start() function do in multithreading in Java?
    We have discussed that Java threads are typically created using one of the two methods : (1) Extending thread class. (2) Implementing RunnableIn both the approaches, we override the run() function, but we start a thread by calling the start() function. So why don't we directly call the overridden ru
    2 min read
    Java Thread Priority in Multithreading
    Java being Object-Oriented works within a Multithreading environment in which the thread scheduler assigns the processor to a thread based on the priority of the thread. Whenever we create a thread in Java, it always has some priority assigned to it. Priority can either be given by JVM while creatin
    5 min read
    Joining Threads in Java
    java.lang.Thread class provides the join() method which allows one thread to wait until another thread completes its execution. If t is a Thread object whose thread is currently executing, then t.join() will make sure that t is terminated before the next instruction is executed by the program. If th
    3 min read
    Java Naming a Thread and Fetching Name of Current Thread
    A thread can be referred to as a lightweight process. Assigning descriptive names to threads enhances code readability and simplifies debugging. Now let us discuss the different ways to name a thread in Java.Methods to Set the Thread NameThere are two ways by which we can set the name either be it d
    4 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences