The Python standard library provides two modules: _thread and threading. _thread is a low-level module, and threading is a high-level module that encapsulates _thread. For the most part, we just need to use the threading high-level module.
Method 1: Pass in a function and create an instance of Thread, then call start() to start execution
import threading
def loop() :
for i in range(30) :print(threading.current_thread().name + "-" + str(i))
threadA = threading.Thread(target=loop, name="Thread A")
threadB = threading.Thread(target=loop, name="Thread B")
threadA.start()
threadB.start()
Copy the code
The following screenshot shows the execution result:
Method 2:Define a class that inherits from the threading.thread class, uses init(self) to initialize it, writes the program to be executed by the Thread in the run(self) method, and then calls start() to execute it
"Have a problem and no one to answer it? We have created a Python learning QQ group: 778463939 to find like-minded friends and help each other. There are also good video tutorials and PDF e-books in the group. ' ' '
import threading
class MyThread(threading.Thread) :
def __init__(self, name) :
threading.Thread.__init__(self)
self.name = name
def run(self) :
for i in range(20) :print(threading.current_thread().name + "-" + str(i))
threadA = MyThread("Thread A")
threadB = MyThread("Thread B")
threadA.start()
threadB.start()
Copy the code
The following screenshot shows the execution result:As you can see, the order of threads A and B is mixed in the output.