新建
- 创建线程对象
就绪
- 调用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