python多线程之事件Event的使用详解


当前第2页 返回上一页

场景:当小伙伴a,b,c集结完毕后,请客的人发话:开吃咯!

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

# coding:utf-8

 

import threading

import time

 

event = threading.Event()

 

 

def chiHuoGuo(name):

  # 等待事件,进入等待阻塞状态

  print '%s 已经启动' % threading.currentThread().getName()

  print '小伙伴 %s 已经进入就餐状态!'%name

  time.sleep(1)

  event.wait()

  # 收到事件后进入运行状态

  print '%s 收到通知了.' % threading.currentThread().getName()

  print '%s 小伙伴 %s 开始吃咯!'%(time.time(), name)

 

 

class myThread (threading.Thread):  # 继承父类threading.Thread

  def __init__(self, name):

    '''重写threading.Thread初始化内容'''

    threading.Thread.__init__(self)

 

    self.people = name

 

  def run(self):  # 把要执行的代码写到run函数里面 线程在创建后会直接运行run函数

    '''重写run方法'''

 

    chiHuoGuo(self.people)   # 执行任务

    print("qq交流群:226296743")

    print("结束线程: %s" % threading.currentThread().getName())

 

# 设置线程组

threads = []

# 创建新线程

thread1 = myThread("a")

thread2 = myThread("b")

thread3 = myThread("c")

 

# 添加到线程组

threads.append(thread1)

threads.append(thread2)

threads.append(thread3)

 

# 开启线程

for thread in threads:

  thread.start()

 

time.sleep(0.1)

# 发送事件通知

print '集合完毕,人员到齐了,开吃咯!'

event.set()

运行结果:

Thread-1 已经启动
小伙伴 a 已经进入就餐状态!
Thread-2 已经启动
小伙伴 b 已经进入就餐状态!
Thread-3 已经启动
小伙伴 c 已经进入就餐状态!
集合完毕,人员到齐了,开吃咯!
Thread-1 收到通知了.
1516780957.47 小伙伴 a 开始吃咯!
qq交流群:226296743
结束线程: Thread-1
Thread-3 收到通知了.
1516780957.47 小伙伴 c 开始吃咯!Thread-2 收到通知了.
qq交流群:226296743

1516780957.47 小伙伴 b 开始吃咯!结束线程: Thread-3

qq交流群:226296743
结束线程: Thread-2

相关推荐:

python线程池threadpool的实现

以上就是python多线程之事件Event的使用详解的详细内容,更多文章请关注木庄网络博客!!

返回前面的内容

相关阅读 >>

Python检验jarque-bera是否符合正态分布

Python进阶看什么书

Python如何清空列表?清空列表的4种方法(代码示例)

Python迭代器和生成器区别

Python文本特征抽取与向量化算法学习实例详解

Python中怎么运行shell脚本

Python的单线程多任务的实现

Python如何合并两个列表?

Python如何使用urllib/urllib2访问http的get及post详解

怎么把pycharm卸载干净

更多相关阅读请进入《Python》频道 >>




打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...