

{"id":125945,"date":"2023-11-15T15:17:10","date_gmt":"2023-11-15T09:47:10","guid":{"rendered":"https:\/\/data-flair.training\/blogs\/?p=125945"},"modified":"2024-02-29T14:30:22","modified_gmt":"2024-02-29T09:00:22","slug":"how-to-create-thread-using-thread-class-in-python","status":"publish","type":"post","link":"https:\/\/data-flair.training\/blogs\/how-to-create-thread-using-thread-class-in-python\/","title":{"rendered":"How to Create Thread using Thread Class in Python"},"content":{"rendered":"<p>Starting our hands-on journey with Python, this tutorial focuses on making threads using the Thread class\u2014an 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.<\/p>\n<p>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.<\/p>\n<h2>Topic Explanation:<\/h2>\n<p>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.<\/p>\n<p>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.<\/p>\n<h3>Prerequisite:<\/h3>\n<ul>\n<li>Basic understanding of Python programming.<\/li>\n<li>Familiarity with basic programming concepts such as functions and classes.<\/li>\n<li>A working Python environment on your computer.<\/li>\n<li>Knowledge of basic concurrency concepts (recommended but not mandatory).<\/li>\n<li>A code editor, such as VSCode or PyCharm, for writing and executing Python scripts.<\/li>\n<\/ul>\n<h3>Code With Comments:<\/h3>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\"># Importing necessary modules for threading and time operations\r\nimport threading\r\nimport time\r\nfrom threading import Thread\r\n\r\n# Defining a custom thread class MyThread1 that inherits from Thread\r\nclass MyThread1(Thread):\r\n    def run(self):\r\n        print(\"\\nThis is MyThread1\")\r\n        # Looping from 1 to 10, printing thread-specific message and sleeping for 1 second\r\n        for i in range(1, 11):\r\n            print(\"\\nMyThread1: \", i)\r\n            time.sleep(1)\r\n\r\n# Defining another custom thread class MyThread2 that also inherits from Thread\r\nclass MyThread2(Thread):\r\n    def run(self):\r\n        print(\"\\nThis is MyThread2\")\r\n        # Looping from 1 to 10, printing thread-specific message and sleeping for 1 second\r\n        for i in range(1, 11):\r\n            print(\"\\nMyThread2: \", i)\r\n            time.sleep(1)\r\n\r\n# Instantiating objects of the custom thread classes\r\nt1 = MyThread1()\r\nt2 = MyThread2()\r\n\r\n# Starting the threads concurrently\r\nt1.start()\r\nt2.start()\r\n\r\n# Recording the start time\r\nstart = time.time()\r\n\r\n# Waiting for the threads to complete using join\r\nt1.join()\r\nt2.join()\r\n\r\n# Recording the end time\r\nend = time.time()\r\n\r\n# Printing the total time taken for the execution of both threads\r\nprint(end - start)<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<p>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.<\/p>\n<p>This is MyThread1<br \/>\nThis is MyThread2<\/p>\n<p><strong>MyThread1:<\/strong> 1<br \/>\n<strong>MyThread2:<\/strong> 1<br \/>\n<strong>MyThread1:<\/strong> 2<br \/>\n<strong>MyThread2:<\/strong> 2<br \/>\n<strong>MyThread1:<\/strong> 3<br \/>\n<strong>MyThread2:<\/strong> 3<br \/>\n<strong>MyThread1:<\/strong> 4<br \/>\n<strong>MyThread2:<\/strong> 4<br \/>\n<strong>MyThread1:<\/strong> 5<br \/>\n<strong>MyThread2:<\/strong> 5<br \/>\n<strong>MyThread1:<\/strong> 6<br \/>\n<strong>MyThread2:<\/strong> 6<br \/>\n<strong>MyThread1:<\/strong> 7<br \/>\n<strong>MyThread2:<\/strong> 7<br \/>\n<strong>MyThread1:<\/strong> 8<br \/>\n<strong>MyThread2:<\/strong> 8<br \/>\n<strong>MyThread1<\/strong>: 9<br \/>\n<strong>MyThread2:<\/strong> 9<br \/>\n<strong>MyThread1:<\/strong> 10<br \/>\n<strong>MyThread2:<\/strong> 10<br \/>\n10.01738166809082<\/p>\n<h3>Code Explanation:<\/h3>\n<ul>\n<li>The code begins by importing necessary modules for threading (threading) and time operations (time).<\/li>\n<li>Two custom thread classes, MyThread1 and MyThread2, are defined, both inheriting from the Thread class.<\/li>\n<li>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.<\/li>\n<li>Objects t1 and t2 are instantiated from MyThread1 and MyThread2 classes.<\/li>\n<li>The start method is called on each thread, initiating their execution concurrently.<\/li>\n<li>The time.time() function is used to record the start and end times.<\/li>\n<li>The join method is called on each thread, ensuring the main thread waits for their completion.<\/li>\n<li>The total time taken for the execution of both threads is calculated and printed.<\/li>\n<\/ul>\n<h3>Conclusion:<\/h3>\n<p>In conclusion, as we conclude this exploration into Python&#8217;s practical side, this tutorial has comprehensively covered the creation of threads using the Thread class\u2014an essential component in concurrent programming.<\/p>\n<p>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.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Starting our hands-on journey with Python, this tutorial focuses on making threads using the Thread class\u2014an important part of doing multiple things at once in Python. Threads help run tasks at the same time,&#46;&#46;&#46;<\/p>\n","protected":false},"author":581,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[46],"tags":[28932,28930,28931,10333,28626],"class_list":["post-125945","post","type-post","status-publish","format-standard","hentry","category-python","tag-creating-thread-in-python","tag-creating-thread-using-thread-class","tag-how-to-create-thread-using-thread-class-in-python","tag-python","tag-python-practical"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v27.8 - https:\/\/yoast.com\/product\/yoast-seo-wordpress\/ -->\n<title>How to Create Thread using Thread Class in Python - DataFlair<\/title>\n<meta name=\"description\" content=\"This foundational knowledge will empower programmers to leverage the advantages of concurrent programming.\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/data-flair.training\/blogs\/how-to-create-thread-using-thread-class-in-python\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"How to Create Thread using Thread Class in Python - DataFlair\" \/>\n<meta property=\"og:description\" content=\"This foundational knowledge will empower programmers to leverage the advantages of concurrent programming.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/data-flair.training\/blogs\/how-to-create-thread-using-thread-class-in-python\/\" \/>\n<meta property=\"og:site_name\" content=\"DataFlair\" \/>\n<meta property=\"article:publisher\" content=\"https:\/\/www.facebook.com\/DataFlairWS\/\" \/>\n<meta property=\"article:published_time\" content=\"2023-11-15T09:47:10+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2024-02-29T09:00:22+00:00\" \/>\n<meta name=\"author\" content=\"DataFlair Team\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@DataFlairWS\" \/>\n<meta name=\"twitter:site\" content=\"@DataFlairWS\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"DataFlair Team\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"3 minutes\" \/>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"How to Create Thread using Thread Class in Python - DataFlair","description":"This foundational knowledge will empower programmers to leverage the advantages of concurrent programming.","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/data-flair.training\/blogs\/how-to-create-thread-using-thread-class-in-python\/","og_locale":"en_US","og_type":"article","og_title":"How to Create Thread using Thread Class in Python - DataFlair","og_description":"This foundational knowledge will empower programmers to leverage the advantages of concurrent programming.","og_url":"https:\/\/data-flair.training\/blogs\/how-to-create-thread-using-thread-class-in-python\/","og_site_name":"DataFlair","article_publisher":"https:\/\/www.facebook.com\/DataFlairWS\/","article_published_time":"2023-11-15T09:47:10+00:00","article_modified_time":"2024-02-29T09:00:22+00:00","author":"DataFlair Team","twitter_card":"summary_large_image","twitter_creator":"@DataFlairWS","twitter_site":"@DataFlairWS","twitter_misc":{"Written by":"DataFlair Team","Est. reading time":"3 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/data-flair.training\/blogs\/how-to-create-thread-using-thread-class-in-python\/#article","isPartOf":{"@id":"https:\/\/data-flair.training\/blogs\/how-to-create-thread-using-thread-class-in-python\/"},"author":{"name":"DataFlair Team","@id":"https:\/\/data-flair.training\/blogs\/#\/schema\/person\/c187795dc82ab948373cca526df7c445"},"headline":"How to Create Thread using Thread Class in Python","datePublished":"2023-11-15T09:47:10+00:00","dateModified":"2024-02-29T09:00:22+00:00","mainEntityOfPage":{"@id":"https:\/\/data-flair.training\/blogs\/how-to-create-thread-using-thread-class-in-python\/"},"wordCount":576,"commentCount":0,"publisher":{"@id":"https:\/\/data-flair.training\/blogs\/#organization"},"keywords":["creating thread in python","creating thread using thread class","How to Create Thread using Thread Class in Python","Python","python practical"],"articleSection":["Python Tutorials"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/data-flair.training\/blogs\/how-to-create-thread-using-thread-class-in-python\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/data-flair.training\/blogs\/how-to-create-thread-using-thread-class-in-python\/","url":"https:\/\/data-flair.training\/blogs\/how-to-create-thread-using-thread-class-in-python\/","name":"How to Create Thread using Thread Class in Python - DataFlair","isPartOf":{"@id":"https:\/\/data-flair.training\/blogs\/#website"},"datePublished":"2023-11-15T09:47:10+00:00","dateModified":"2024-02-29T09:00:22+00:00","description":"This foundational knowledge will empower programmers to leverage the advantages of concurrent programming.","breadcrumb":{"@id":"https:\/\/data-flair.training\/blogs\/how-to-create-thread-using-thread-class-in-python\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/data-flair.training\/blogs\/how-to-create-thread-using-thread-class-in-python\/"]}]},{"@type":"BreadcrumbList","@id":"https:\/\/data-flair.training\/blogs\/how-to-create-thread-using-thread-class-in-python\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Blog Home","item":"https:\/\/data-flair.training\/blogs\/"},{"@type":"ListItem","position":2,"name":"Python Tutorials","item":"https:\/\/data-flair.training\/blogs\/category\/python\/"},{"@type":"ListItem","position":3,"name":"How to Create Thread using Thread Class in Python"}]},{"@type":"WebSite","@id":"https:\/\/data-flair.training\/blogs\/#website","url":"https:\/\/data-flair.training\/blogs\/","name":"DataFlair","description":"Learn Today. Lead Tomorrow.","publisher":{"@id":"https:\/\/data-flair.training\/blogs\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/data-flair.training\/blogs\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/data-flair.training\/blogs\/#organization","name":"DataFlair","url":"https:\/\/data-flair.training\/blogs\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/data-flair.training\/blogs\/#\/schema\/logo\/image\/","url":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2016\/07\/Data-Flair.png","contentUrl":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2016\/07\/Data-Flair.png","width":106,"height":48,"caption":"DataFlair"},"image":{"@id":"https:\/\/data-flair.training\/blogs\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/www.facebook.com\/DataFlairWS\/","https:\/\/x.com\/DataFlairWS","https:\/\/www.linkedin.com\/company\/dataflair-web-services-pvt-ltd\/","https:\/\/www.youtube.com\/user\/DataFlairWS"]},{"@type":"Person","@id":"https:\/\/data-flair.training\/blogs\/#\/schema\/person\/c187795dc82ab948373cca526df7c445","name":"DataFlair Team","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/secure.gravatar.com\/avatar\/2302ebc438084d2f1f993edc1996a0aae01332e81f3227cba8df0c48ec010ca4?s=96&d=mm&r=g","url":"https:\/\/secure.gravatar.com\/avatar\/2302ebc438084d2f1f993edc1996a0aae01332e81f3227cba8df0c48ec010ca4?s=96&d=mm&r=g","contentUrl":"https:\/\/secure.gravatar.com\/avatar\/2302ebc438084d2f1f993edc1996a0aae01332e81f3227cba8df0c48ec010ca4?s=96&d=mm&r=g","caption":"DataFlair Team"},"description":"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.","url":"https:\/\/data-flair.training\/blogs\/author\/dfteam6\/"}]}},"amp_enabled":true,"_links":{"self":[{"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/posts\/125945","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/users\/581"}],"replies":[{"embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/comments?post=125945"}],"version-history":[{"count":3,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/posts\/125945\/revisions"}],"predecessor-version":[{"id":134281,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/posts\/125945\/revisions\/134281"}],"wp:attachment":[{"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/media?parent=125945"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/categories?post=125945"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/tags?post=125945"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}