本文摘自php中文网,作者云罗郡主,侵删。
本篇文章给大家带来的内容是关于python多线程的两种实现方式(代码教程),有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助。
线程是轻量级的进程,进程中可划分出多个线程,线程可独立的调度运行(进程中分割出来的可以独立运行的实例) 例如:我们的电脑cpu可以同时运行qq和微信,qq运行时可以同时打开多个聊天框. 在上述例子中qq 微信及进程,每个聊天框为不同的线程
第一种:
利用threading中的Thread方法实现
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | 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函数**
1 2 3 4 5 6 7 8 9 10 11 | 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()
|
以上就是对python多线程的两种实现方式(代码教程)的全部介绍,如果您想了解更多有关Python视频教程,请关注PHP中文网。
以上就是python多线程的两种实现方式(代码教程)的详细内容,更多文章请关注木庄网络博客!!
相关阅读 >>
Python中strip什么意思
Python怎么安装matplotlib
介绍Python爬取网页
numpy中以文本的方式存储以及读取数据方法
Python如何识别图片中的文字
pandas妙招之 dataframe基础运算以及空值填充
洞悉 Python基础概况
Python中的特殊变量__name__有什么用?
Python使用tesseract库实现识别验证
Python如何保留2位小数
更多相关阅读请进入《Python》频道 >>
人民邮电出版社
python入门书籍,非常畅销,超高好评,python官方公认好书。
转载请注明出处:木庄网络博客 » python多线程的两种实现方式(代码教程)