/, Tech/Python – using Thread in a Subclass

Python – using Thread in a Subclass

Implement a New Thread Using the Threading Module

  • Define a new subclass of the Thread class
  • Override the __init__(self [, args]) method to add additional arguments
  • Override the run(self [,args]) method to implement what the thread should do when it is started.
  • When this is done, you can start a new thread by invoking the start method which will in turn call the run method
import threading
import time

exit_flag = 0

class myThread(threading.Thread):
    def __init__(self, threadId, name, counter):
        self.threadId = threadId
        self.name = name
        self.counter = counter

    def run(self):
        print("Starting " + self.name  + "\n")
        print_time(self.name, self.counter, 5)
        print("Exiting " + self.name + "\n")

def print_time(threadName, delay, counter):
    while counter:
        if exit_flag:
        print("%s : %s" % (threadName, time.ctime(time.time())))
        counter -= 1

# main program
if __name__ == '__main__':
    # create two threads

    thread1 = myThread(1, "thread-1", 1)
    thread2 = myThread(2, "thread-2", 2)



    print("Exiting main thread")
  • The threading module is the preferred module for creating and managing threads.
  • Each thread is represented by a class that extends the thread class and overrides its run method.
  • Then this run method becomes the starting point of the thread.
  • Calling the constructor of thread class is mandatory.
  • Using it, we can redefine some properties like name or group of the thread.
  • The thread is placed in active state at the call to start method and remains there until it ends the run method or you throw an unhandled exception


Starting thread-1

Starting thread-2

thread-1 : Sun Dec  2 22:11:04 2018
thread-2 : Sun Dec  2 22:11:05 2018
thread-1 : Sun Dec  2 22:11:05 2018
thread-1 : Sun Dec  2 22:11:06 2018
thread-2 : Sun Dec  2 22:11:07 2018
thread-1 : Sun Dec  2 22:11:07 2018
thread-1 : Sun Dec  2 22:11:08 2018
Exiting thread-1

thread-2 : Sun Dec  2 22:11:09 2018
thread-2 : Sun Dec  2 22:11:11 2018
thread-2 : Sun Dec  2 22:11:13 2018
Exiting thread-2

Exiting main thread
By |2018-12-02T22:28:36+00:00December 2nd, 2018|Categories: Python, Tech|Tags: , , |0 Comments

About the Author:

Pratik Kataria is currently learning Springboot and Hibernate. Technologies known and worked on: C/C++, Java, Python, JavaScript, HTML, CSS, Wordpress, Angular, Ionic, MongoDB, SQL and Android. Softwares known and worked on: Adobe Photoshop, Adobe Illustrator and Adobe After Effects.

Leave A Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.