python怎么能同时执行代码(多线程)?

2025-05-14 07:40:34
推荐回答(1个)
回答(1):

import _thread # 引入线程包

# 1. 定义线程

def 线程1名字():

    # 在这个地方写线程1要干嘛......


def 线程2名字():

    # 在这个地方写线程2要干嘛......


def 线程3名字():

    # 在这个地方写线程3要干嘛......


# 以此类推....


# 2. 启动这些线程

_thread.start_new_thread(线程1名字,())

_thread.start_new_thread(线程2名字,())

_thread.start_new_thread(线程3名字,())


# 以此类推....

# 启动之后这些线程都是同时执行的

# 如果某个线程函数有参数需要传入,可使用:

_thread.start_new_thread(某线程名字,(参数1,参数2...) )