Python创建多线程的两种常用方法总结

经过总结,python创建多线程主要有如下两种方法:

  • 函数

接下来,我们就来揭开多线程的神秘面纱。

1. 用函数创建多线程

在Python3中,Python提供了一个内置模块 threading.Thread,可以很方便地让我们创建多线程。

threading.Thread() 一般接收两个参数:

  • 线程函数名:要放置线程让其后台执行的函数,由我们自已定义,注意不要加();
  • 线程函数的参数:线程函数名所需的参数,以元组的形式传入。若不需要参数,可以不指定。

举个例子

  1. import time
  2. from threading import Thread
  3.  
  4. # 自定义线程函数。
  5. def target(name=“Python”):
  6.      for i in range(2):
  7.          print(“hello”, name)
  8.          time.sleep(1)
  9.  
  10. # 创建线程01,不指定参数
  11. thread_01 = Thread(target=target)
  12. # 启动线程01
  13. thread_01.start()
  14.  
  15.  
  16. # 创建线程02,指定参数,注意逗号
  17. thread_02 = Thread(target=target, args=(“MING”,))
  18. # 启动线程02
  19. thread_02.start()

可以看到输出

hello Python
hello MING
hello Python
hello MING

2. 用类创建多线程

相比较函数而言,使用类创建线程,会比较麻烦一点。

首先,我们要自定义一个类,对于这个类有两点要求,

  • 必须继承 threading.Thread 这个父类;
  • 必须复写 run 方法。

这里的 run 方法,和我们上面线程函数的性质是一样的,可以写我们的业务逻辑程序。在 start() 后将会调用。

来看一下例子 为了方便对比,run函数我复用上面的main。

  1. import time
  2. from threading import Thread
  3.  
  4. class MyThread(Thread):
  5.      def __init__(self, type=“Python”):
  6.          # 注意:super().__init__() 必须写
  7.          # 且最好写在第一行
  8.          super().__init__()
  9.          self.type=type
  10.  
  11.      def run(self):
  12.          for i in range(2):
  13.              print(“hello”, self.type)
  14.              time.sleep(1)
  15.  
  16. if __name__ == ‘__main__’:
  17.      # 创建线程01,不指定参数
  18.      thread_01 = MyThread()
  19.      # 创建线程02,指定参数
  20.      thread_02 = MyThread(“MING”)
  21.  
  22.      thread_01.start()
  23.      thread_02.start()

当然结果也是一样的。

hello Python
hello MING
hello Python
hello MING

3. 线程对象的方法

上面介绍了当前 Python 中创建线程两种主要方法。

创建线程是件很容易的事,但要想用好线程,还需要学习线程对象的几个函数。

经过我的总结,大约常用的方法有如下这些:

  1. # 如上所述,创建一个线程
  2. t=Thread(target=func)
  3.  
  4. # 启动子线程
  5. t.start()
  6.  
  7. # 阻塞子线程,待子线程结束后,再往下执行
  8. t.join()
  9.  
  10. # 判断线程是否在执行状态,在执行返回True,否则返回False
  11. t.is_alive()
  12. t.isAlive()
  13.  
  14. # 设置线程是否随主线程退出而退出,默认为False
  15. t.daemon = True
  16. t.daemon = False
  17. # 设置线程名
  18. t.name = “My-Thread”

到此这篇关于Python创建多线程的两种常用方法总结的文章就介绍到这了,更多相关Python创建多线程内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!

标签

发表评论