1. 程式人生 > >python 兩個執行緒交替執行

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()

獲取對方的鎖,執行完後釋放自己的鎖;