標籤:import sleep false 通訊
使用threading.Event可以使一個線程等待其他線程的通知,
把這個Event傳遞到線程對象中,Event預設內建了一個標誌,初始值為False。一旦該線程通過wait()方法進入等待狀態,直到另一個線程調用該Event的set()方法將內建標誌設定為True時,該Event會通知所有等待狀態的線程恢複運行。
import threading
import time
class MyThread(threading.Thread):
def __init__(self, signal):
threading.Thread.__init__(self)
self.singal = signal
def run(self):
print "I am %s,I will sleep ..."%self.name
self.singal.wait()
print "I am %s, I awake..." %self.name
if __name__ == "__main__":
singal = threading.Event()
for t in range(0, 3):
thread = MyThread(singal)
thread.start()
print "main thread sleep 3 seconds... "
time.sleep(3)
singal.set()
運行效果:
I am Thread-1,I will sleep ...
I am Thread-2,I will sleep ...
I am Thread-3,I will sleep ...
main thread sleep 3 seconds...
I am Thread-1, I awake...I am Thread-2, I awake...
I am Thread-3, I awake...
本文出自 “qianc81115” 部落格,請務必保留此出處http://qianc81115.blog.51cto.com/10067995/1629186
Python使用Event線程間通訊