Python中的start()方法与join()方法的区别及用法
发布时间:2023-12-29 05:40:38
start()方法与join()方法是Python中用于管理多线程的两个重要方法。
start()方法用于启动一个线程,它会调用线程的run()方法并使其并发执行。每次调用start()方法时,都会启动一个新线程,并发执行多个线程。
join()方法用于等待线程的结束。在主线程中调用join()方法时,主线程会阻塞,直到被调用线程执行完毕。
下面是一个简单的例子,通过使用start()方法和join()方法来创建并发执行的线程:
import threading
def thread_function(name):
print("Thread %s starts" % name)
time.sleep(2)
print("Thread %s ends" % name)
threads = []
# 创建并启动5个线程
for i in range(5):
thread = threading.Thread(target=thread_function, args=(i,))
thread.start()
threads.append(thread)
# 等待所有线程执行完毕
for thread in threads:
thread.join()
print("All threads have ended")
上述代码中,我们定义了一个函数thread_function()作为线程的执行函数。在主线程中,我们创建了5个线程,每个线程都会调用thread_function()函数,并传入一个不同的参数。然后我们启动这些线程,将它们添加到一个列表中。最后,我们使用join()方法等待所有线程执行完毕,然后输出一条信息表示所有线程已经结束。
输出结果可能会有所不同,但是会类似如下:
Thread 0 starts Thread 1 starts Thread 2 starts Thread 3 starts Thread 4 starts Thread 0 ends Thread 3 ends Thread 2 ends Thread 1 ends Thread 4 ends All threads have ended
可以看到,所有线程都同时启动,并且在不同的时间结束。主线程在所有线程执行完毕之前会阻塞,等待它们执行完毕。
总结起来,start()方法用于启动一个线程,使其并发执行,而join()方法用于等待线程的结束。通过这两个方法,我们可以方便地管理和控制各个线程的执行。
