python 两个线程交替执行

import threading
import time

def a():
    while True:
        lockb.acquire()
        print('a')
        locka.release()
        time.sleep(0.5)


def b():
    while True:
        locka.acquire()
        print('b')
        lockb.release()
        time.sleep(0.5)


if __name__ == "__main__":
    locka = threading.Lock()
    lockb = threading.Lock()

    ta = threading.Thread(None, a)
    tb = threading.Thread(None, b)

    locka.acquire()     #保证a先执行

    ta.start()
    tb.start()

获取对方的锁,运行完后释放自己的锁;

猜你喜欢

转载自blog.csdn.net/M_N_N/article/details/81321233