• 技术文章 >Python技术 >Python基础教程

    threading在python中创建线程的两种方式

    小妮浅浅小妮浅浅2021-05-13 09:38:09原创2637

    1、直接通过初始化thread对象创建:

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    15

    16

    17

    18

    19

    20

    #coding=utf-8

    import threading,time

      

    def test():

    t = threading.currentThread()  # 获取当前子线程对象

    print t.getName()  # 打印当前子线程名字

      

    i=0

    while i<10:

         print i

         time.sleep(1)

         i=i+1

      

      

      

      

    m=threading.Thread(target=test,args=(),name='循环子线程')   #初始化一个子线程对象,target是执行的目标函数,args是目标函数的参数,name是子线程的名字

    m.start()

    t=threading.currentThread()   #获取当前线程对象,这里其实是主线程

    print t.getName()   #打印当前线程名字,其实是主线程名字

    2、通过基础thread类来创建,需要创建一个自定义线程

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    15

    16

    17

    18

    19

    20

    21

    22

    23

    24

    25

    26

    27

    28

    import threading,time

    class myThread (threading.Thread):   #创建一个自定义线程类mythread,继承Thread

      

    def __init__(self,name):

        """

        重新init方法

        :param name: 线程名

        """

        super(myThread, self).__init__(name=name)

        # self.lock=lock

      

        print '线程名'+name

      

    def run(self):

        """

        重新run方法,这里面写我们的逻辑

        :return:

        """

        i=0

        while i<10:

            print i

            time.sleep(1)

            i=i+1

      

      

    if __name__=='__main__':

    t=myThread('mythread')

    t.start()

    以上就是threading在python中创建线程的两种方式,希望能对大家有所帮助。更多Python学习指路:python基础教程

    本文教程操作环境:windows7系统、Python 3.9.1,DELL G3电脑。

    专题推荐:python threading
    上一篇:python中使用Dockerfile构建镜像 下一篇:python中sys模块怎么用?

    相关文章推荐

    • Python中的threading模块是什么• python多线程中的threading使用技巧• Python并集是什么意思?• Python交集有什么作用?• Python常用的画布方法• Python画笔的属性有哪些?• python中使用Dockerfile构建镜像

    全部评论我要评论

    © 2021 Python学习网 苏ICP备2021003149号-1

  • 取消发布评论
  • 

    Python学习网