运维辞典@欢迎访问小站,如有疑问,可通过右侧QQ或底部邮箱联系,非常感谢@

python多线程示例代码

Python Administrator 485℃

oldmain()单线程,依次执行任务
newmain()多线程,同时执行任务

from time import sleep, ctime
import threading

def music(func, loop):
    for i in range(loop):
        print("i was listening to %s %s " % (func, ctime()))
        sleep(2)

def movie(func, loop):
    for i in range(loop):
        print("i was at the %s %s " % (func, ctime()))
        sleep(5)

def oldmain():
    print("begin1:", ctime())
    music("我要飞",2)
    movie("阿凡达",2)
    print("end1:",ctime())

def newmain():
    print("begin2:", ctime())
    threads = []
    t1 = threading.Thread(target=music, args=("我要飞",2))
    threads.append(t1)
    t2 = threading.Thread(target=movie, args=("阿凡达", 2))
    threads.append(t2)

    for t in threads:
        t.start()
    for t in threads:
        t.join()
    print("end2:", ctime())


if __name__ == '__main__':
    oldmain()
    newmain()

执行结果:
begin1: Thu Aug 16 14:31:43 2018
i was listening to 我要飞 Thu Aug 16 14:31:43 2018
i was listening to 我要飞 Thu Aug 16 14:31:45 2018
i was at the 阿凡达 Thu Aug 16 14:31:47 2018
i was at the 阿凡达 Thu Aug 16 14:31:52 2018
end1: Thu Aug 16 14:31:57 2018
单线程花费了14秒
begin2: Thu Aug 16 14:31:57 2018
i was listening to 我要飞 Thu Aug 16 14:31:57 2018
i was at the 阿凡达 Thu Aug 16 14:31:57 2018
i was listening to 我要飞 Thu Aug 16 14:31:59 2018
i was at the 阿凡达 Thu Aug 16 14:32:02 2018
end2: Thu Aug 16 14:32:07 2018
多线程花费了10秒

码字很辛苦,转载请注明来自:《运维辞典 » python多线程示例代码

喜欢 (0)