python多线程怎样执行函数

2025-03-25 01:27:54
推荐回答(2个)
回答(1):

  1. 将你需要多线程并发执行的函数放入list中

    import threading

    threads = []

    t1 = threading.Thread(target=函数名,args=参数)
    threads.append(t1)

  2. 启动多线程

    if __name__ == '__main__':
            for t in threads:
                t.setDaemon(True)
                t.start()
    t.join()

  3. 更多详细操作help(threading)

  4. #coding=utf-8
    import threading
    from time import ctime,sleep

    # 要启动的函数
    def music(func):
        for i in range(2):
            print "I was listening to %s. %s" %(func,ctime())
            sleep(1)
    # 要启动的函数
    def move(func):
        for i in range(2):
            print "I was at the %s! %s" %(func,ctime())
            sleep(5)

    threads = []
    t1 = threading.Thread(target=music,args=(u'爱情买卖',))
    threads.append(t1)
    t2 = threading.Thread(target=move,args=(u'阿凡达',))
    threads.append(t2)
    # 函数加入线程列表
    if __name__ == '__main__':
        for t in threads:
            t.setDaemon(True)
            t.start()
    t.join() #子线程完成运行之前,这个子线程的父线程将一直被阻塞,不会退出
        print "all over %s" %ctime()

回答(2):

正常执行 但是线程运行状态不受函数的控制