0% found this document useful (0 votes)
6 views10 pages

Skip To Content10

Uploaded by

raroy67751
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views10 pages

Skip To Content10

Uploaded by

raroy67751
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 10

Skip to content

geeksforgeeks
Courses 90% Refund
Tutorials
Java
Practice
Contests

Sign In

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

Content Improvement Event


Share Your Experiences
Java Tutorial
Overview of Java
Basics of Java
Input/Output in Java
Flow Control in Java
Operators in Java
Strings in Java
Arrays in Java
OOPS in Java
Inheritance in Java
Abstraction in Java
Encapsulation in Java
Polymorphism in Java
Constructors in Java
Methods in Java
Interfaces in Java
Wrapper Classes in Java
Keywords in Java
Access Modifiers in Java
Memory Allocation in Java
Classes of Java
Packages in Java
Java Collection Tutorial
Exception Handling in Java
Multithreading in Java
Multithreading in Java
Lifecycle and States of a Thread in Java
Java Thread Priority in Multithreading
Main thread in Java
Java.lang.Thread Class in Java
Runnable interface in Java
Naming a thread and fetching name of current thread in Java
What does start() function do in multithreading in Java?
Difference between Thread.start() and Thread.run() in Java
Thread.sleep() Method in Java With Examples
Synchronization in Java
File Handling in Java
Java Regex
Java IO
Java Networking
JDBC - Java Database Connectivity
Java 8 Features - Complete Tutorial
Java Backend DevelopmentCourse
Naming a thread and fetching name of current thread in Java
Last Updated : 25 Jun, 2022
Thread can be referred to as a lightweight process. Thread uses fewer resources to
create and exist in the process; thread shares process resources. The main thread
of Java is the thread that is started when the program starts. now let us discuss
the eccentric concept of with what ways we can name a thread.

Methods: There are two ways by which we can set the name either be it directly or
indirectly which we will be peeking through.

Creating the thread and Passing the thread’s name (Direct method)
Using setName() method of Thread class (Indirect Method)
Method 1: Creating the thread and passing the thread’s name

It is a direct method of naming threads in java, each thread has a name that is:
Thread-0, Thread-1, Thread-2,….so on. Java provides some methods to change the
thread name. There are basically two methods to set the thread name. Both methods
are defined in java.lang.Thread class.

Geek, now you must be wondering how to set the thread’s name directly? In java we
can set the thread name at the time of creating the thread and bypassing the
thread’s name as an argument as shown in the below example as follows:

Example:

Java

// Java Program Illustrating How to Set the name


// of Thread at time of Creation

// Importing I/O classes from java.io package


import java.io.*;

// Class 1
// Helper class
class ThreadNaming extends Thread {

// Parameterized constructor
ThreadNaming(String name)
{
// Call to constructor of
// the Thread class as super keyword
// refers to parent class
super(name);
}
// run() method for thread
@Override public void run()
{
// Print statement when thread is called inside
// main()
System.out.println("Thread is running.....");
}
}

// Class 2
// Main class
class GFG {

// main driver method


public static void main(String[] args)
{

// Creating two threads


ThreadNaming t1 = new ThreadNaming("geek1");
ThreadNaming t2 = new ThreadNaming("geek2");

// Getting the above created threads names.


System.out.println("Thread 1: " + t1.getName());
System.out.println("Thread 2: " + t2.getName());

// Starting threads using start() method


t1.start();
t2.start();
}
}
Output
Thread 1: geek1
Thread 2: geek2
Thread is running.....
Thread is running.....
Way 2: Using setName() method of Thread class

We can set(change) the thread’s name by calling the setName method on that thread
object. It will change the name of a thread.

Syntax:

public final void setName(String name)


Parameter: A string that specifies the thread name

Example:

Java

// Java Program Illustrating How to Get and Change the


// Name of a Thread

// Importing input output classes


import java.io.*;

// Class 1
// Helper class extending Thread class
class ThreadNaming extends Thread {
// run() method for thread which is called
// as soon as start() is called over threads
@Override public void run()
{

// Print statement when run() is called over thread


System.out.println("Thread is running.....");
}
}

// Class 2
// Main class
class GFG {

// Main driver method


public static void main(String[] args)
{

// Creating two threads via above class


// as it is extending Thread class
ThreadNaming t1 = new ThreadNaming();
ThreadNaming t2 = new ThreadNaming();

// Fetching the above created threads names


// using getName() method
System.out.println("Thread 1: " + t1.getName());
System.out.println("Thread 2: " + t2.getName());

// Starting threads using start() method


t1.start();
t2.start();

// Now changing the name of threads


t1.setName("geeksforgeeks");
t2.setName("geeksquiz");

// Again getting the new names of threads


System.out.println(
"Thread names after changing the "
+ "thread names");

// Printing the above names


System.out.println("New Thread 1 name: "
+ t1.getName());
System.out.println("New Thread 2 name: "
+ t2.getName());
}
}
Output
Thread 1: Thread-0
Thread 2: Thread-1
Thread is running.....
Thread names after changing the thread names
New Thread 1 name: geeksforgeeks
New Thread 2 name: geeksquiz
Thread is running.....
How to fetch the name of the current thread?
Now let us dwell on fetching the name of the current thread. We can fetch the
current thread name at the time of creating the thread and bypassing the thread’s
name as an argument.

Method: currentThread()

It is defined in java.langThread class.

Return Type: It returns a reference to the currently executing thread

Syntax:

public static Thread currentThread()


Example:

Java

// Java program to Illustrate How to Get Name of


// Current Executing thread
// Using getName() Method

// Importing reqiored I/O classes


import java.io.*;

// Class 1
// Helper class extending to Thread class
class ThreadNaming extends Thread {

// run() method for this thread


@Override public void run()
{
// Display message
System.out.println(
"Fetching current thread name..");

// Getting the current thread name


// using getname() method
System.out.println(
Thread.currentThread().getName());
}
}

// Class 2
// Main class
class GFG {

// Main method driver


public static void main(String[] args)
{

// Creating two threads inside main() method


ThreadNaming t1 = new ThreadNaming();
ThreadNaming t2 = new ThreadNaming();

// Starting threads using start() method which


// automatically calls run() method
t1.start();
t2.start();
}
}
Output
Fetching current thread name..
Thread-0
Fetching current thread name..
Thread-1

Three 90 Challenge is back on popular demand! After processing refunds worth INR
1CR+, we are back with the offer if you missed it the first time. Get 90% course
fee refund in 90 days. Avail now!
Want to be a master in Backend Development with Java for building robust and
scalable applications? Enroll in Java Backend and Development Live Course by
GeeksforGeeks to get your hands dirty with Backend Programming. Master the key Java
concepts, server-side programming, database integration, and more through hands-on
experiences and live projects. Are you new to Backend development or want to be a
Java Pro? This course equips you with all you need for building high-performance,
heavy-loaded backend systems in Java. Ready to take your Java Backend skills to the
next level? Enroll now and take your development career to sky highs.

Hello friends, welcome to Geeks forPlay Video

Nitsdheerendra

17
Previous Article
Runnable interface in Java
Next Article
What does start() function do in multithreading in Java?
Read More
Down Arrow
Similar Reads
Why Thread.stop(), Thread.suspend(), and Thread.resume() Methods are Deprecated
After JDK 1.1 Version?
The Thread class contains constructors and methods for creating and operating on
threads. Thread is a subclass of Object that implements the Runnable interface.
There are many methods in Thread Class but some of them are deprecated as of JDK
1.1. In this article, we will understand the reason behind it. Deprecated methods
are those that are no long
5 min read
java.rmi.Naming Class in Java
Java.rmi.Naming class contains a method to bind, unbind or rebind names with a
remote object present at the remote registry. This class is also used to get the
reference of the object present at remote registries or the list of name associated
with this registry. Syntax: Class declaration public final class Naming extends
Object Let us do discuss s
4 min read
Difference between Thread.start() and Thread.run() in Java
In Java's multi-threading concept, start() and run() are the two most important
methods. Below are some of the differences between the Thread.start() and
Thread.run() methods: New Thread creation: When a program calls the start() method,
a new thread is created and then the run() method is executed. But if we directly
call the run() method then no
3 min read
Interface Naming Conflicts in Java
Interfaces in Java consist of abstract methods (which do not contain a body) and
variables (which are public static final). Implementation of the methods of the
interface is defined in classes that implement that interface. It helps Java to
achieve abstraction. Naming Conflicts occur when a class implements two interfaces
that have methods and vari
5 min read
Naming Conventions in Java
A programmer is always said to write clean codes, where naming has to be
appropriate so that for any other programmer it acts as an easy way out to read the
code. At a smaller level, this seems meaningless but think of the industrial level
where it becomes necessary to write clean codes in order to save time for which
there are certain rules been l
5 min read
Get name of current method being executed in Java
Getting name of currently executing method is useful for handling exceptions and
debugging purposes. Below are different methods to get currently executing method :
Using Throwable Stack Trace : Using Throwable Class : In Java, Throwable class is
the superclass of all exceptions and errors in java.lang package. Java Throwable
class provides several
4 min read
Servlet - Fetching Result
Servlet is a simple java program that runs on the server and is capable to handle
requests from the client and generate dynamic responses for the client. How to
Fetch a Result in Servlet? It is depicted below stepwise as shown below as follows:
You can fetch a result of an HTML form inside a Servlet using request object's
getParameter() method.requ
3 min read
Fetching Updates From a Remote Repository Using JGit
JGit is a lightweight Java library that can be implemented for Git version control
systems. It allows developers to perform Git operations programmatically within
Java applications. One of the essential tasks in Git is fetching updates from a
remote repository, ensuring that the local repository stays in sync with the remote
repository. This articl
3 min read
Best Practices For Naming API Endpoints in a RESTful Architecture
Naming API endpoints is important in designing a clear and easy-to-use API. By
using consistent and descriptive names, avoiding abbreviations, and following best
practices for pluralization and lowercase letters, you can create an API that is
easy to understand, use, and maintain. Naming API endpoints is an important part of
designing a RESTful API
6 min read
Myth about the file name and class name in Java
The first lecture note given during java class is “In java file name and class name
should be the same”. When the above law is violated a compiler error message will
appear as below Java Code /***** File name: Trial.java ******/ public class Geeks {
public static void main(String[] args) { System.out.println("Hello
world"); } } Output: ja
3 min read
Article Tags :
Java
Practice Tags :
Java
three90RightbarBannerImg
course-img
215k+ interested Geeks
Master Java Programming - Complete Beginner to Advanced
Explore
course-img
214k+ interested Geeks
JAVA Backend Development - Live
Explore
course-img
30k+ interested Geeks
Manual to Automation Testing: A QA Engineer's Guide
Explore
geeksforgeeks-footer-logo
Corporate & Communications Address:- A-143, 9th 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
Company
About Us
Legal
Careers
In Media
Contact Us
Advertise with us
GFG Corporate Solution
Placement Training Program
Explore
Job-A-Thon Hiring Challenge
Hack-A-Thon
GfG Weekly Contest
Offline Classes (Delhi/NCR)
DSA in JAVA/C++
Master System Design
Master CP
GeeksforGeeks Videos
Geeks Community
Languages
Python
Java
C++
PHP
GoLang
SQL
R Language
Android Tutorial
DSA
Data Structures
Algorithms
DSA for Beginners
Basic DSA Problems
DSA Roadmap
DSA Interview Questions
Competitive Programming
Data Science & ML
Data Science With Python
Data Science For Beginner
Machine Learning Tutorial
ML Maths
Data Visualisation Tutorial
Pandas Tutorial
NumPy Tutorial
NLP Tutorial
Deep Learning Tutorial
Web Technologies
HTML
CSS
JavaScript
TypeScript
ReactJS
NextJS
NodeJs
Bootstrap
Tailwind CSS
Python Tutorial
Python Programming Examples
Django Tutorial
Python Projects
Python Tkinter
Web Scraping
OpenCV Tutorial
Python Interview Question
Computer Science
GATE CS Notes
Operating Systems
Computer Network
Database Management System
Software Engineering
Digital Logic Design
Engineering Maths
DevOps
Git
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
School Subjects
Mathematics
Physics
Chemistry
Biology
Social Science
English Grammar
Commerce
Accountancy
Business Studies
Economics
Management
HR Management
Finance
Income Tax
Databases
SQL
MYSQL
PostgreSQL
PL/SQL
MongoDB
Preparation Corner
Company-Wise Recruitment Process
Resume Templates
Aptitude Preparation
Puzzles
Company-Wise Preparation
Companies
Colleges
Competitive Exams
JEE Advanced
UGC NET
UPSC
SSC CGL
SBI PO
SBI Clerk
IBPS PO
IBPS Clerk
More Tutorials
Software Development
Software Testing
Product Management
Project Management
Linux
Excel
All Cheat Sheets
Recent Articles
Free Online Tools
Typing Test
Image Editor
Code Formatters
Code Converters
Currency Converter
Random Number Generator
Random Password Generator
Write & Earn
Write an Article
Improve an Article
Pick Topics to Write
Share your Experiences
Internships
@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
Got It !
Lightbox

You might also like