Python program for multithreading with class

Here, we will write a Python program for multithreading using class.
Submitted by Shivang Yadav, on March 19, 2021

A thread is a block of code that can run independently.

Multithreading is the process of running multiple threads simultaneously to increase the program's speed.

Threads can be run using class, by making a class object a thread that can run independently.

Python program for multithreaded with class

import threading
import time

class Car(threading.Thread):
   def init(self):
       self.i=0

   def run(self):
      i=1
      while(i<=10):
         if(self.getName()=="Ciaz"):
           time.sleep(1)
         if (self.getName() == "Swift" and self.i >= 3):
             break

         print(self.getName(),"Car Is Running....")
         i+=1
         self.i+=1

swift=Car()
swift.init()
swift.setName("Swift")
swift.start()

ciaz=Car()
ciaz.init()
ciaz.setName("Ciaz")
ciaz.start()

Output:

Swift Car Is Running....
Swift Car Is Running....
Swift Car Is Running....
Ciaz Car Is Running....
Ciaz Car Is Running....
Ciaz Car Is Running....
Ciaz Car Is Running....
Ciaz Car Is Running....
Ciaz Car Is Running....
Ciaz Car Is Running....
Ciaz Car Is Running....
Ciaz Car Is Running....
Ciaz Car Is Running....

Python Threading Programs »





Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.