python多线程

基于多线程的木头人游戏,等待时间随机

 1 import threading
 2 import time
 3 import random
 4 
 5 def game():
 6     x=random.randint(1,10)
 7     print(x)
 8     count = 0
 9     period =0
10     time_count=0
11     while True:
12         if time_count< 20:
13             if count < x:
14                 event.set()
15                 print("\033[42;1mmoving\033[0m")
16                 count+=1
17             elif period<5:
18                 event.clear()
19                 print("\033[41;1m木头人do not moving\033[0m")
20                 period+=1
21             else:
22                 print("\033[42;1mmoving\033[0m")
23                 period =0
24                 count=0
25                 x = random.randint(1,10)
26             time.sleep(1)
27             time_count+=1
28         else:
29             print("time out,game over!!!")
30             break
31 
32 def run(num,name):
33     while True:
34         if event.is_set():
35             print("%s is moving"%name)
36             time.sleep(num)
37         else:
38             print("%s is waiting"%name)
39             event.wait()
40 
41 
42 if __name__ == '__main__':
43     event = threading.Event()
44 
45     g1=threading.Thread(target=game,)
46     p1=threading.Thread(target=run,args=(1,"dog"))
47     p2=threading.Thread(target=run,args=(1.5,"cat"))
48     p1.setDaemon(True)
49     p2.setDaemon(True)
50     g1.start()
51     p1.start()
52     p2.start()

 

 

posted @ 2019-04-25 13:03  竹心_兰君  阅读(174)  评论(0编辑  收藏  举报