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

    python多线程的实现方式

    宋雪维宋雪维2021-02-22 09:21:13原创5866

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

    方法一:创建threading.Thread对象

    1

    2

    3

    4

    5

    6

    7

    8

    9

    import threading

    def tstart(arg):

        print(f"{arg}running" )

    if __name__ == '__main__':

        t1 = threading.Thread(target=tstart, args=('This is thread 1',))

        t2 = threading.Thread(target=tstart, args=('This is thread 2',))

        t1.start()

        t2.start()

        print("This is main function")

    方法二:继承于threading.Thread,重写方法run()

    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

    import threading

    import time

     

     

    # 重写一个类,继承于threading.Thread

    class MyThread(threading.Thread):

        def __init__(self, jobName):

            super(MyThread, self).__init__()

            self.jobName = jobName

     

        # 重写run方法, 实现多线程, 因为start方法执行时, 调用的是run方法;

        # run方法里面编写的内容就是你要执行的任务;

        def run(self):

            print("这是一个需要执行的任务%s。。。。。" %(self.jobName))

            print("当前线程的个数:", threading.active_count() )

            time.sleep(1)

            print("当前线程的信息:", threading.current_thread())

    if __name__ == '__main__':

        t1 = MyThread("name1")

        t2 = MyThread("name2")

        t1.start()

        t2.start()

        t1.join()

        t2.join()

        print("程序执行结束.....")

    以上就是python多线程的两种实现方法,大家可以根据具体情况选择不同的实现方法,希望能对你有所帮助哦~

    专题推荐:python基础python多线程
    上一篇:python中求平方根的方法 下一篇:python多线程和多进程之间的联系

    相关文章推荐

    • 理解python中的random.choice()• python中random模块将列表内容打乱• python中random模块常见函数有哪几种?• python中count函数是什么意思?• python中翻译功能translate模块• Python中translate( ) 方法的实现原理• python中求平方根的方法

    全部评论我要评论

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

  • 取消发布评论
  • 

    Python学习网