Home »
Python »
Python Reference »
Python Thread class
Python Thread run() Method with Example
Python Thread.run() Method: In this tutorial, we will learn about the run() method of Thread class in Python with its usage, syntax, and examples.
By Hritika Rajput Last updated : April 24, 2023
Python Thread.run() Method
The Thread.run() method is an inbuilt method of the Thread class of the threading module , it is used to represent a thread's activity. It calls the method expressed as the target argument in the Thread object along with the positional and keyword arguments taken from the args and kwargs arguments, respectively. This method can also be overridden in the subclass.
Module
The following module is required to use run() method:
import threading
Class
The following class is required to use run() method:
from threading import Thread
Syntax
The following is the syntax of run() method:
run()
Parameter(s)
The following are the parameter(s):
Return Value
The return type of this method is <class 'NoneType'>, it returns nothing.
Example of Thread.run() Method in Python
# Python program to explain the
# use of run() method in Thread class
import threading
def thread_1(i):
print('Value by Thread 1:', i)
def thread_2(i):
print('Value by Thread 2:', i)
def thread_3(i):
print('Value by Thread 3:', i)
# Creating three sample threads
thread1 = threading.Thread(target=thread_1, args=(1,))
thread2 = threading.Thread(target=thread_2, args=(2,))
thread3 = threading.Thread(target=thread_3, args=(3,))
# Running three thread object
thread1.run()
thread2.run()
thread3.run()
Output
Value by Thread 1: 1
Value by Thread 2: 2
Value by Thread 3: 3
run() method can also be overridden in the subclass. Given below creates a subclass of the Thread class and overrides the run function.
Example 2
# Python program to demonstrate
# the overriding of run() method
import threading
class mythread(threading.Thread):
def __init__(self, thread_name, thread_ID):
threading.Thread.__init__(self)
self.thread_name = thread_name
self.thread_ID = thread_ID
# Overrriding of run() method in the subclass
def run(self):
print("Thread name: "+str(self.thread_name) +" "+ "Thread id: "+str(self.thread_ID));
thread1 = mythread("thread1", 1)
thread2 = mythread("thread2", 2);
thread1.start()
thread2.start()
Output
Thread name: thread1 Thread id: 1
Thread name: thread2 Thread id: 2