Python Thread getName() Method with Example

Python Thread.getName() Method: In this tutorial, we will learn about the getName() method of Thread class in Python with its usage, syntax, and examples. By Hritika Rajput Last updated : April 24, 2023

Python Thread.getName() Method

The Thread.getName() method is an inbuilt method of the Thread class of the threading module, it is used to get the name of the thread.

Module

The following module is required to use getName() method:

import threading

Class

The following class is required to use getName() method:

from threading import Thread

Syntax

The following is the syntax of getName() method:

getName()

Parameter(s)

The following are the parameter(s):

  • None

Return Value

The return type of this method is <class 'str'>, it returns thread name of the calling object.

Example of Thread.getName() Method in Python

# Python program to explain the
# use of getName() method

import time
import threading

def thread_1(i):
    time.sleep(5)
    print('Value by '+ str(threading.current_thread().getName())+" is: ", i)

def thread_2(i):
    print('Value by '+ str(threading.current_thread().getName())+" is: ", i)
    
def thread_3(i):
    time.sleep(4)
    print('Value by '+ str(threading.current_thread().getName())+" is: ", i)
    
# Creating three sample threads 
thread1 = threading.Thread(target=thread_1, args=(10,))
thread2 = threading.Thread(target=thread_2, args=(20,))
thread3 = threading.Thread(target=thread_2, args=(30,))

# Running the threads
thread1.start()
thread2.start()
thread3.start()

Output

Value by Thread-2 is:  20
Value by Thread-3 is:  30
Value by Thread-1 is:  10

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.