【python随笔】之【两个线程交替打印数字(线程的事件与通信)】

it2024-05-15  45

import threading import time def go1(): with con: # 先运行,先锁定 for i in range(0, 10, 2): time.sleep(1) print(threading.current_thread().name, i) con.wait() # 等待 con.notify() # 通知打印完成 def go2(): with con: # 后运行,等待解锁 for i in range(1, 10, 2): time.sleep(1) print(threading.current_thread().name, i) con.notify() # 通知打印完成 con.wait() # 等待 con = threading.Condition() threading.Thread(target=go1).start() threading.Thread(target=go2).start() Thread-1 0 Thread-2 1 Thread-1 2 Thread-2 3 Thread-1 4 Thread-2 5 Thread-1 6 Thread-2 7 Thread-1 8 Thread-2 9
最新回复(0)