python多线程交替打印abc

还是元气满满的小黄鸭呀! 利用python线程的互斥锁可以把资源锁住,然后一个时间只让一个线程执行 【python多线程交替打印abc】关于缓冲区问题:使用 print 输出时会先把数据放到缓冲区里,只有当程序结束时或缓冲区遇到 \n 时,才将数据显示到屏幕,并清空缓冲区,而 print 函数默认会有 \n。
关于换行和缓冲区问题的详细解释:https://blog.csdn.net/yilovexing/article/details/80845514

import threading import sys import time def showa(): while True: lockc.acquire()#获取对方的锁,释放自己的锁 print('a',end='') sys.stdout.flush()#释放缓冲区 locka.release() time.sleep(0.2) def showb(): while True: locka.acquire() print('b',end='') sys.stdout.flush() lockb.release() time.sleep(0.2) def showc(): while True: lockb.acquire() print('c',end='') sys.stdout.flush() lockc.release() time.sleep(0.2) if __name__=='__main__': locka=threading.Lock()#定义3个互斥锁 lockb=threading.Lock() lockc=threading.Lock()t1=threading.Thread(target=showa)#定义3个线程 t2=threading.Thread(target=showb) t3=threading.Thread(target=showc)locka.acquire()#先锁住a,b锁,保证先打印a lockb.acquire()t1.start() t2.start() t3.start()执行结果:abcabcabcabcabcabcabcabcabcabcbabcabcabcabcabcabc.......

    推荐阅读