这篇文章主要讲解了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()
获取对方的锁,运行完后释放自己的锁
补充知识:线程同步——两个线程轮流执行python实现
看代码!
import threading
import time
lockA=threading.Lock()
lockB=threading.Lock()
def printA(n):
if n<0:
return
lockA.acquire()
print("+++")
lockB.release()
time.sleep(0.1)
printA(n-1)
def printB(n):
if n<0:
return
lockB.acquire()
print("***")
lockA.release()
time.sleep(0.2)
printB(n-1)
lockB.acquire()
t1=threading.Thread(target=printA,args=(10,))
t2=threading.Thread(target=printB,args=(10,))
t1.start()
t2.start()
t1.join()
t2.join()
看完上述内容,是不是对python如何实现两个线程交替执行有进一步的了解,如果还想学习更多内容,欢迎关注亿速云行业资讯频道。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。