首页 > 编程语言 >Python简单实现多线程例子

Python简单实现多线程例子

时间:2024-06-07 12:21:49浏览次数:10  
标签:Thread thread Python stop threading 例子 线程 print 多线程

使用Python实现多线程的例子,演示如何在主线程内分别启动ABC三个线程,并实现启动和停止指定线程的功能

``
import threading
import time

  # 定义一个全局标志,用于控制线程的运行状态
  stop_thread_A = False
  stop_thread_B = False
  stop_thread_C = False

  # 线程A的函数
  def thread_A():
      while not stop_thread_A:
          print("Thread A is running")
          time.sleep(1)
      print("Thread A is stopped")

  # 线程B的函数
  def thread_B():
      while not stop_thread_B:
          print("Thread B is running")
          time.sleep(1)
      print("Thread B is stopped")

  # 线程C的函数
  def thread_C():
      while not stop_thread_C:
          print("Thread C is running")
          time.sleep(1)
      print("Thread C is stopped")

  # 启动线程的函数
  def start_threads():
      global thread_a, thread_b, thread_c

      # 创建线程
      thread_a = threading.Thread(target=thread_A)
      thread_b = threading.Thread(target=thread_B)
      thread_c = threading.Thread(target=thread_C)

      # 启动线程
      thread_a.start()
      thread_b.start()
      thread_c.start()

  # 停止指定线程的函数
  def stop_thread(thread_name):
      global stop_thread_A, stop_thread_B, stop_thread_C

      if thread_name == 'A':
          stop_thread_A = True
      elif thread_name == 'B':
          stop_thread_B = True
      elif thread_name == 'C':
          stop_thread_C = True

  if __name__ == "__main__":
      # 启动ABC三个线程
      start_threads()

      # 主线程等待5秒
      time.sleep(5)

      # 停止线程A
      stop_thread('A')

      # 主线程等待5秒
      time.sleep(5)

      # 停止线程B和C
      stop_thread('B')
      stop_thread('C')

      # 确保所有线程已经停止
      thread_a.join()
      thread_b.join()
      thread_c.join()

      print("All threads have been stopped")

``
注意事项
线程安全:在多线程编程中,访问和修改共享资源时要小心,以避免竞态条件和数据不一致问题。使用锁(Lock)可以确保线程安全。
停止线程的方式:使用标志变量来控制线程的停止是一个常见的方法,避免使用强制终止线程的方法(如threading.Thread的terminate()),因为这可能会导致资源未正确释放等问题。
线程的生命周期:确保主线程在退出前等待所有子线程结束,使用join()方法可以确保这一点。
这个示例展示了如何使用Python的threading模块来启动和停止线程,并解释了相关的注意事项和代码细节。

标签:Thread,thread,Python,stop,threading,例子,线程,print,多线程
From: https://www.cnblogs.com/mac666888/p/18237010

相关文章

  • Python数据分析常用开源库 pycharm
    内容介绍Pandas数据处理的库,可以做可视化文件类数据交互的是比较好的CSVExcel环境搭建起来SeriesDataFrame前3天主要介绍DataFrame的使用(Pandas的API)第四天数据可视化day05~day08Pandas解决数据分析问题报表,取数(SQL,Pandas,Excel)业务分析能......
  • python各种加解密方法
    #-*-encoding:utf-8-*-fromhashlibimportmd5importbase64#MD5加密obj=md5()str="你是个小可爱"obj.update(str.encode("utf-8"))#obj.update("wusir".encode('utf-8'))#可以添加多个被加密的内容bs=obj.hexdigest()print("md5......
  • 8-4 【Python0036】中文级联菜单
    importtkinterastkfromtkinterimportttkfrompypinyinimportlazy_pinyin#省份、城市、地区数据data={"北京":{"北京市":["东城区","西城区","朝阳区"],},"上海":{"上海市......
  • 用 Python 撸一个 Web 服务器-第9章:项目总结
    项目总结本教程带大家一起实现了一个TodoList程序,包含基础的增删改查功能,和用户登录认证。这也是Web开发中最常见的需求。我画了一张思维导图,帮助你从宏观的角度来概览TodoList程序,加深你对Web开发的理解。TodoList项目整体思路参考MVC设计模式。有意设计utils......
  • 用 Python 撸一个 Web 服务器-第8章:用户管理
    用户登录原理用户登录与注册功能几乎已成为Web应用的标配。所以我们有必要给TodoList程序增加一个用户管理模块,以此来学习用户登录原理。HTTP协议是无状态的,这意味着每个完整的HTTP请求——响应过程都是相对独立的,Web服务器无法分辨前后两次连续请求是否为同一个用户......
  • 用 Python 撸一个 Web 服务器-第7章:重构——更好的组织代码
    通过前几章的学习,我们完成了TodoList程序的todo管理部分,实现了对todo的增、删、改、查基本操作,这也是几乎所有Web程序都具备的功能。我们当然可以按照目前的思路继续来实现用户管理部分,在models.py中编写用户相关的模型,在templates/目录下新建用户相关HTML,在contro......
  • 【已解决】Python报错Pytorch:ModuleNotFoundError: No module named ‘torch’
    本文摘要:本文已解决Pytorch:ModuleNotFoundError:Nomodulenamed‘torch’的相关报错问题,并总结提出了几种可用解决方案。同时结合人工智能GPT排除可能得隐患及错误。......
  • 【已解决】Python报错 ERROR: Could not find a version that satisfies the requirem
    本文摘要:本文已解决ERROR:Couldnotfindaversionthatsatisfiestherequirement的相关报错问题,并总结提出了几种可用解决方案。同时结合人工智能GPT排除可能得隐患及错误。......
  • Python进阶:解密collections库的高级功能
    Python内置库collections提供了一些强大的工具类,可以简化和优化我们的编程过程。本文将重点探索collections库中的几个类的使用。通过详细的代码示例和解释,展示如何利用Counter计数和统计元素,以及如何使用defaultdict创建有默认值的字典。一、常见类的介绍Pythoncollections......
  • 《手把手教你》系列练习篇之12-python+ selenium自动化测试(详细教程)
    1.简介前面文章我们了解了如何获取元素的text属性值,和判断元素是否显示在页面(is_displayed()方法),本文我们来学习下,判断一个控件是否被选中状态、获取页面元素的大小、组合键-全选文字、组合键-退格键删除文本和鼠标右键等练习的内容。2.验证控件是否被选中还是以百度......