Creating Custom Thread in Python

Previous
Next

Multi threaded application:

  • Define a Custom thread and execute along with Default thread.
  • Every Custom thread inherits the functionality from “Thread” class.
  • “Thread” class is belongs to “threading” module.
  • We must define thread logic by overriding run() method of Thread class.
    class Thread:
        def run(self):
            # empty
            return

    class Custom(Thread):
        def run(self):
            # thread logic
            return

The following example is used to display numbers parallel using Default thread and Custom thread:

from threading import Thread
class Custom(Thread):
    def run(self):
        for i in range(50):
            print("Custom :",i)
        return

class Default:
    def main():
        obj = Custom()
        obj.start()
        for j in range(50):
            print("Default :",j)
        return

Default.main()
  • In the above example, we separate the message and value with comma(,) operator.
  • When we use comma(,) operator, it consider as 2 different statements and the output will be clumsy.
  • In the following example, we merge the message and value using str() method.
from threading import Thread
class Custom(Thread):
    def run(self):
        for i in range(50):
            print("Custom :" + str(i))
        return

class Default:
    def main():
        obj = Custom()
        obj.start()
        for j in range(50):
            print("Default :" + str(j))
        return

Default.main()
Previous
Next

Add Comment

Courses Enquiry Form