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

    python threading实现线程的过程

    小妮浅浅小妮浅浅2021-08-30 09:19:53原创2138

    过程说明

    1、从Thread类构成子类。覆盖方法根据需要提供参数。

    2、重写线程的业务逻辑。

    3、新的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

    29

    30

    31

    32

    33

    34

    35

    #Python 多线程示例打印当前日期。

    #1. 使用 threading.Thread 类定义子类。

    #2. 实例化子类并触发线程。

      

    import threading

    import datetime

      

    class myThread (threading.Thread):

        def __init__(self, name, counter):

            threading.Thread.__init__(self)

            self.threadID = counter

            self.name = name

            self.counter = counter

        def run(self):

            print("\nStarting " + self.name)

            print_date(self.name, self.counter)

            print("Exiting " + self.name)

      

    def print_date(threadName, counter):

        datefields = []

        today = datetime.date.today()

        datefields.append(today)

        print("{}[{}]: {}".format( threadName, counter, datefields[0] ))

      

    # 创建新线程

    thread1 = myThread("Thread", 1)

    thread2 = myThread("Thread", 2)

      

    # 启动新线程

    thread1.start()

    thread2.start()

      

    thread1.join()

    thread2.join()

    print("\nExiting the Program!!!")

    以上就是python threading实现线程的过程,希望对大家有所帮助。更多Python学习指路:python基础教程

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

    专题推荐:python threading
    上一篇:python thread模块创建线程 下一篇:python threading线程同步如何实现

    相关文章推荐

    • python中Roberts算子是什么• python中Prewitt算子如何理解• python中Sobel算子是什么• python中Sobel算子如何使用• python中Laplacian算子如何使用• python中Laplacian算子是什么• python输入函数input的使用• python控制语句的两大分类• python编写程序的常见错误• python用户如何自定义异常• python thread模块创建线程

    全部评论我要评论

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

  • 取消发布评论
  • 

    Python学习网