线程间的交互:事件Event
线程间的交互:
事件event:用于线程间的交互,如:A线程要等待B线程运行完之后再运行,就可以在B线程中e.set,A线程中设置e.wait
方法:
event.isSet():返回event状态值False或True
event.wait()如果event状态为False,将阻塞线程
event.set()默认设定event为True
event.clear()恢复event的状态为False
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
from threading import Thread,Event import os,time e = Event() def light(): time.sleep(5) print('light is fun') e.set() def car(): print('<%s> the car is waiting '%os.getpid()) e.wait() print('<%s> the car is running'%os.getpid()) if __name__ == '__main__': for i in range(10): t = Thread(target=car) t.start() t2 = Thread(target=light) t2.start()
定时器timer
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
from threading import Timer def hello(): print("hello, world") t = Timer(1, hello) t.start() # after 1 seconds, "hello, world" will be printed
队列Queue
class queue.
PriorityQueue
(maxsize=0) #存储数据时可设置优先级的队列
class queue.
LifoQueue
(maxsize=0) #last in fisrt out
class queue.
Queue
(maxsize=0) #先进先出