python多线程的两种实现方式(代码教程)


本文摘自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中pass的作用是什么

如何使用Python处理json数据

利用Python如何爬取js里面的内容

Python count函数用法详解

Python if else用法是什么?

Python中列表,元组 ,集合 ,字典之间的区别

Python中property函数的简单介绍

Python培训机构哪家比较正规

编辑器vs怎么样

Python用户验证怎么弄

更多相关阅读请进入《Python》频道 >>




打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...