How to start a thread in Python?
To initiate a thread in Python, you can use the threading module. Here is a simple example code:
import threading
def print_numbers():
for i in range(1, 11):
print(i)
def print_letters():
for letter in 'abcdefghij':
print(letter)
# 创建线程
t1 = threading.Thread(target=print_numbers)
t2 = threading.Thread(target=print_letters)
# 启动线程
t1.start()
t2.start()
# 等待线程结束
t1.join()
t2.join()
In the above code, print_numbers and print_letters are two functions used for printing numbers and letters, respectively. Then, two threads are created using threading.Thread, each specifying the function to be executed. Finally, the threads are started using the start method and the join method is used to wait for the threads to finish.
Note: multiple threads can execute concurrently, but the order of execution between threads is unpredictable.