3-17 多线程实践应用

多线程

多线程(MultiThreading)是指从软件或者硬件上实现多个线程并发执行的技术。

 

案例:让学生同时进行说和写操作

 

from time import ctime, sleep

import threading


# 定义说和写方法
def talk(content, loop):
    for i in range(loop):
        print("开始说:%s %s" % (content, ctime()))
        sleep(2)


def write(content, loop):
    for i in range(loop):
        print("开始写:%s %s" % (content, ctime()))
        sleep(2)


# 定义和装载说和写的线程
threads = []
t1 = threading.Thread(target=talk, args=('不要怂一起上', 2))
threads.append(t1)

t2 = threading.Thread(target=write, args=('人生苦短,我用Python', 3))
threads.append(t2)

# 执行多线程
if __name__ == '__main__':
    for t in threads:
        t.start()
    for t in threads:
        t.join()
    print("所有线程执行完成!%s" % ctime())

 

 

 

 

posted @ 2020-12-14 16:56  Trinamic-一蓑烟雨  阅读(73)  评论(0编辑  收藏  举报