郑州Python培训机构:两种实现方式表现python多线程
来源:
奇酷教育 发表于:
郑州Python培训机构老师给大家带来的内容是关于python多线程的两种实现方式(代码教程),有一定的参考价值,有需要的朋友可以参考一下
郑州Python培训机构老师给大家带来的内容是关于python多线程的两种实现方式(代码教程),有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助。
线程是轻量级的进程,进程中可划分出多个线程,线程可独立的调度运行(进程中分割出来的可以独立运行的实例) 例如:我们的电脑cpu可以同时运行qq和微信,qq运行时可以同时打开多个聊天框. 在上述例子中qq 微信及进程,每个聊天框为不同的线程

第一种:
利用threading中的Thread方法实现
import threadingimport timedef eat():
# 循环打印,延迟一秒
while True:
print("我在吃饭")
time.sleep(1)def drink():
while True:
print("我在喝水")
time.sleep(1)def main():
thr1 = threading.Thread(target=eat)
thr2 = threading.Thread(target=drink) # 创建并执行线程
thr1.start()
thr2.start()if __name__ == '__main__':
main()
**第二种:
利用threading中的Timer函数**
import timeimport threadingdef eat():
# 循环打印
while True:
print("我在吃饭") # 延迟一秒
time.sleep(1)def drink():
while True:
print("我在喝水")
time.sleep(1)# 创建延迟触发,第一个参数为设置几秒后开始,第二个是执行函数名thr1 = threading.Timer(1, eat)
thr2 = threading.Timer(1, drink)
thr1.start()
thr2.start()