ADVERTISEMENT
ADVERTISEMENT

Python Thread Class | run() Method with Example

Python Thread.run() Method: Here, we are going to learn about the run() method of Thread class in Python with its definition, syntax, and examples.
Submitted by Hritika Rajput, on May 07, 2020

Python Thread.run() Method

Thread.run() method is an inbuilt method of the Thread class of the threading module in Python. This method 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:

    from threading import Thread

Syntax:

    run()

Parameter(s):

  • None

Return value:

The return type of this method is <class 'NoneType'>, it returns nothing.

Example:

# 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:

# 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
ADVERTISEMENT



ADVERTISEMENT



Comments and Discussions


ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.