线程之间的执行顺序是无序的

  1. import threading
  2. import time
  3. def rask():
  4. time.sleep(1)
  5. print(threading.current_thread())
  6. pass
  7. if __name__ == '__main__':
  8. for item in range(5):
  9. rask_threading = threading.Thread(target=rask)
  10. rask_threading.start()
  11. pass
  • 执行结果
  1. <Thread(Thread-2, started 18756)>
  2. <Thread(Thread-1, started 20816)>
  3. <Thread(Thread-4, started 18496)>
  4. <Thread(Thread-3, started 7556)>
  5. <Thread(Thread-5, started 20920)>

主线程会等待子线程执行完结果

  • 如果子线程是一个死循环的话?
  • 让子线程守护主线程demaon(就可以结束死循环)
  1. import threading
  2. import time
  3. def rask():
  4. while True:
  5. print("正在执行中.....")
  6. time.sleep(0.2)
  7. pass
  8. pass
  9. if __name__ == '__main__':
  10. # 方法一:
  11. # rask_threading = threading.Thread(target=rask, daemon=True)
  12. rask_threading = threading.Thread(target=rask)
  13. # 方法二
  14. rask_threading.setDaemon(True)
  15. rask_threading.start()
  16. time.sleep(1)
  17. print("over")