Python-线程的五种状态

线程的五种状态

新建

  • 创建线程对象

就绪

  • 调用start(),线程成为就绪状态
  • 等待调度程序选定为运行线程
  • 可从阻塞或睡眠、等待的状态转成就绪状态

运行

  • 线程调度程序从可运行池中选择一个线程运行
  • 这也是线程进入运行状态的唯一一种方式。

阻塞

线程被挂起。例如调用sleep(),线程被挂起,睡眠时间结束后,程序到了就绪状态。或者join()阻塞线程,待子线程返回时,主线程再继续执行

def printThreadName():
    for i in range(5):
        print("当前运行的线程:{threadName},执行到第{N}次".format(threadName=threading.currentThread().getName(), N=i) )
myThread=threading.Thread(target=printThreadName)

# 主线程和子线程会轮流获得 CPU 资源
myThread.start()
print("主线程:" + threading.current_thread().getName())

"""
执行的结果:
当前运行的线程:Thread-1,执行到第0次
当前运行的线程:Thread-1,执行到第1次
当前运行的线程:Thread-1,执行到第2次
当前运行的线程:Thread-1,执行到第3次
MainThread  
当前运行的线程:Thread-1,执行到第4次
"""

#阻塞主线程
childrenThread=threading.Thread(target=printThreadName)
childrenThread.start()
childrenThread.join()
print("主线程:" + threading.current_thread().getName())
"""
执行的结果:
当前运行的线程:Thread-1,执行到第0次
当前运行的线程:Thread-1,执行到第1次
当前运行的线程:Thread-1,执行到第2次
当前运行的线程:Thread-1,执行到第3次
当前运行的线程:Thread-1,执行到第4次
MainThread  
"""
  • 线程仍旧是活的(可运行的),但是当前没有条件运行
  • 如果某件事件出现,他可能返回到可运行状态

死亡

  • 当线程的run()方法完成时就认为它死去。
  • 这个线程对象也许是活的,但是,它已经不是一个单独执行的线程。
  • 线程一旦死亡,就不能复生。
    在这里插入图片描述

参考 Python之线程的五种状态
链接:https://blog.csdn.net/weixin_44733660/article/details/103294043

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值