Home »
Python »
Python Reference »
Python Thread class
Python Thread setName() Method with Example
Python Thread.setName() Method: In this tutorial, we will learn about the setName() method of Thread class in Python with its usage, syntax, and examples.
By Hritika Rajput Last updated : April 24, 2023
Python Thread.setName() Method
The Thread.setName() method is an inbuilt method of the Thread class of the threading module, it is used to set the name of the thread.
Module
The following module is required to use setName() method:
import threading
Class
The following class is required to use setName() method:
from threading import Thread
Syntax
The following is the syntax of setName() method:
setName()
Parameter(s)
The following are the parameter(s):
Return Value
The return type of this method is <class 'NoneType'>, it sets the name of the Thread object which calls this method.
Example of Thread.setName() Method in Python
# Python program to explain the
# use of setName() method
import time
import threading
def thread_1(i):
time.sleep(5)
#threading.current_thread.setName("frgrfvrv")
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,))
thread1.setName("Thread_number_1")
thread2 = threading.Thread(target=thread_2, args=(20,))
thread2.setName("Thread_number_2")
thread3 = threading.Thread(target=thread_2, args=(30,))
thread3.setName("Thread_number_3")
# Running the threads
thread1.start()
thread2.start()
thread3.start()
Output
Value by Thread_number_2 is: 20
Value by Thread_number_3 is: 30
Value by Thread_number_1 is: 10