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

 

 

转载于:https://www.cnblogs.com/Dai-py/p/10767813.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值