Execute function
1. Write an executive function to achieve something, different people eat hot pot with a parameter people instead.
# coding=utf-8import threadingimport timedef chiHuoGuo(people): print("%s 吃火锅的小伙伴-羊肉:%s" % (time.ctime(),people)) time.sleep(1) print("%s 吃火锅的小伙伴-鱼丸:%s" % (time.ctime(),people))
Rewrite threading. Thread
1. Use the threading module to create the thread directly from the threading. Thread inherits, and then overrides the __init__ method and the Run method
# Coding=utf-8Import threadingImport timeclass mythread (threading. Thread): # inherits the parent class threading. Thread def __init__ (self, people, name): def run (self): # writes the code to execute into the run function, the thread will run the run function directly after creation "' Rewrite the Run method ' Print ( "Start thread:" + self.threadname) Chihuoguo (self.people) # perform task print (" End Thread: "+ self.name)
Start and run differences
The 1.start () method starts the thread activity.
It can only be called once for each thread object, and it arranges the object to call the Run () method (not the current thread) in an additional separate thread.
When the method is called more than once in the same thread object, a RuntimeError (run-time error) is introduced.
The 2.run () method represents the method of thread activity.
You can override this method in a subclass. The standard run () method invokes the Tunable object passed to the object's constructor as the target parameter, and if so, the order and keyword parameters are obtained from args and Kargs, respectively.
Reference Code
# Coding=utf-8Import threadingImport timeDefChihuoguo(people): print ("%s small pot-eating partner-Lamb:%s"% (Time.ctime (), people)) Time.sleep (1) Print ("%s small pot-eating partner-fish ball:%s"% (Time.ctime (), people))ClassMyThread(Threading. Thread):# inherits the parent class threading. ThreadDef__init__(self, people, name):"' Rewrite threading. Thread initializes the content "' Threading. Thread.__init__ (self) self.threadname = name Self.people = Peopledef run # write the code you want to execute into the run function. The thread runs the run function directly after it is created " overrides the Run method ' Print ( "Start thread:" + self.threadname) Chihuoguo (self.people) # perform task print ( "End Thread:" + self.name) # Create new Thread thread1 = MyThread ( "Sea Sea", "thread A") Thread2 = MyThread ( "Lao Wang", "thread B") # Turn on Thread Thread1.start () Thread2.start () time.sleep (0.5) print ( " Exit main thread ")
Python note 8-multithreaded threading Package