import threading
condition = threading.Condition()
num =100defrun():global num
condition.acquire()while num >0:print("线程{}输出数字{}".format(threading.currentThread().name, num))
num -=1if num ==0:break
condition.notify()if num ==1:break
condition.wait()
condition.release()
t1 = threading.Thread(target=run)
t2 = threading.Thread(target=run)
t1.start()
t2.start()
t1.join()
t2.join()
实现方法二
import threading
from concurrent.futures import ThreadPoolExecutor
condition = threading.Condition()
num =100defrun():global num
with condition:while num >0:print("线程{}输出数字{}".format(threading.currentThread().name, num))
num -=1if num ==0:break
condition.notify()if num ==1:break
condition.wait()with ThreadPoolExecutor(2)as executor:
executor.submit(run)
executor.submit(run)