How to Create Thread using Thread Class in Python

Master Python with 70+ Hands-on Projects and Get Job-ready - Learn Python

Starting our hands-on journey with Python, this tutorial focuses on making threads using the Thread class—an important part of doing multiple things at once in Python. Threads help run tasks at the same time, making programs more efficient by handling several operations simultaneously.

As we navigate through the implementation of threads using the Thread class, this guide aims to provide a hands-on experience for Python enthusiasts, offering a foundational understanding of concurrent programming and the ability to harness the power of threads for improved program performance.

Topic Explanation:

In this tutorial, we will delve into the practical implementation of thread creation using the Thread class in Python. Threads are lightweight, independently executing units that enable concurrent execution of tasks within a program. The tutorial will cover the fundamental concepts of threading, emphasizing the use of the Thread class from the threading module. Through illustrative examples and step-by-step explanations, learners will gain insights into creating, starting, and managing threads in Python. The practical applications of threading, such as parallelizing tasks and improving program responsiveness, will be explored, providing a valuable skill set for programmers aiming to optimize their code through concurrent execution.

By the end of this tutorial, participants will not only comprehend the theoretical underpinnings of threading but also possess the practical know-how to apply threading concepts in real-world Python projects. This foundational knowledge will empower programmers to leverage the advantages of concurrent programming, ultimately leading to more responsive and efficient Python applications.

Prerequisite:

  • Basic understanding of Python programming.
  • Familiarity with basic programming concepts such as functions and classes.
  • A working Python environment on your computer.
  • Knowledge of basic concurrency concepts (recommended but not mandatory).
  • A code editor, such as VSCode or PyCharm, for writing and executing Python scripts.

Code With Comments:

# Importing necessary modules for threading and time operations
import threading
import time
from threading import Thread

# Defining a custom thread class MyThread1 that inherits from Thread
class MyThread1(Thread):
    def run(self):
        print("\nThis is MyThread1")
        # Looping from 1 to 10, printing thread-specific message and sleeping for 1 second
        for i in range(1, 11):
            print("\nMyThread1: ", i)
            time.sleep(1)

# Defining another custom thread class MyThread2 that also inherits from Thread
class MyThread2(Thread):
    def run(self):
        print("\nThis is MyThread2")
        # Looping from 1 to 10, printing thread-specific message and sleeping for 1 second
        for i in range(1, 11):
            print("\nMyThread2: ", i)
            time.sleep(1)

# Instantiating objects of the custom thread classes
t1 = MyThread1()
t2 = MyThread2()

# Starting the threads concurrently
t1.start()
t2.start()

# Recording the start time
start = time.time()

# Waiting for the threads to complete using join
t1.join()
t2.join()

# Recording the end time
end = time.time()

# Printing the total time taken for the execution of both threads
print(end - start)

Output:

In this output, both MyThread1 and MyThread2 are executing concurrently, printing their respective messages and numbers from 1 to 10. The total time taken for the execution of both threads is approximately 10 seconds, as indicated by the time difference between the start and end timestamps. Note that the actual execution times may vary on different runs.

This is MyThread1
This is MyThread2

MyThread1: 1
MyThread2: 1
MyThread1: 2
MyThread2: 2
MyThread1: 3
MyThread2: 3
MyThread1: 4
MyThread2: 4
MyThread1: 5
MyThread2: 5
MyThread1: 6
MyThread2: 6
MyThread1: 7
MyThread2: 7
MyThread1: 8
MyThread2: 8
MyThread1: 9
MyThread2: 9
MyThread1: 10
MyThread2: 10
10.01738166809082

Code Explanation:

  • The code begins by importing necessary modules for threading (threading) and time operations (time).
  • Two custom thread classes, MyThread1 and MyThread2, are defined, both inheriting from the Thread class.
  • The run method in each class prints thread-specific messages in a loop from 1 to 10, with a 1-second sleep between each iteration.
  • Objects t1 and t2 are instantiated from MyThread1 and MyThread2 classes.
  • The start method is called on each thread, initiating their execution concurrently.
  • The time.time() function is used to record the start and end times.
  • The join method is called on each thread, ensuring the main thread waits for their completion.
  • The total time taken for the execution of both threads is calculated and printed.

Conclusion:

In conclusion, as we conclude this exploration into Python’s practical side, this tutorial has comprehensively covered the creation of threads using the Thread class—an essential component in concurrent programming.

This tutorial gives Python enthusiasts practical experience, helping them understand concurrent programming principles and use threads to improve program performance. By learning how to create threads, learners can efficiently handle multiple tasks at the same time, enhancing their skills for real-world Python development.

You give me 15 seconds I promise you best tutorials
Please share your happy experience on Google

courses

DataFlair Team

DataFlair Team provides high-impact content on programming, Java, Python, C++, DSA, AI, ML, data Science, Android, Flutter, MERN, Web Development, and technology. We make complex concepts easy to grasp, helping learners of all levels succeed in their tech careers.

Leave a Reply

Your email address will not be published. Required fields are marked *