首页 > 编程语言 > 详细

python多线程

时间:2019-04-25 13:51:21      阅读:154      评论:0      收藏:0      [点我收藏+]

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

 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()

 

python多线程

原文:https://www.cnblogs.com/Dai-py/p/10767813.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!