线程同步的使用

#coding=utf-8
import threading
import time

#创建三把互斥锁
lock1=threading.Lock()
lock2=threading.Lock()
lock3=threading.Lock()
#lock2  lock3上锁
lock2.acquire()
lock3.acquire()


class Mythread1(threading.Thread):
    def run(self):
        while True:
            if lock1.acquire():      #判断lock1并未上锁,因此这里可以正常上锁,为真,所以后面代码可以执行
                print('...task1...')
                time.sleep(1)
                lock2.release()

class Mythread2(threading.Thread):
    def run(self):
        while True:
            if lock2.acquire():
                print('...task2...')
                time.sleep(1)
                lock3.release()

class Mythread3(threading.Thread):
    def run(self):
        while True:
            if lock3.acquire():
                print('...task3...')
                time.sleep(1)
                lock1.release()


if __name__=='__main__':
    t1=Mythread1()
    t2=Mythread2()
    t3=Mythread3()
    t1.start()
    t2.start()
    t3.start()
    
结果:会循环往复按如下的顺序执行
...task1...
...task2...
...task3...
...task1...
...task2...
...task3...
...task1...
...task2...
...task3...

你可能感兴趣的:(线程同步的使用)