python基于event实现线程间通信控制

yipeiwu_com6年前Python基础

这篇文章主要介绍了python基于event实现线程间通信控制,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下

import threading,time
class Boss(threading.Thread):
  def run(self):
    print("We must work today!")
    event.isSet() or event.set()
    time.sleep(5)
    print("You can go home right now!")
    event.isSet() or event.set()

class Worker(threading.Thread):
  def run(self):
    event.wait()
    print("Oh,my god!!!")
    time.sleep(1)
    event.clear()
    event.wait()
    print("Oh,yeah!!!")
if __name__ == "__main__":
  event = threading.Event()
  threads = []
  for i in range(5):
    threads.append(Worker())
  threads.append(Boss())
  for t in threads:
    t.start()
  for t in threads:
    t.join()

运行后显示:

We must work today!
Oh,my god!!!
Oh,my god!!!
Oh,my god!!!
Oh,my god!!!
Oh,my god!!!
You can go home right now!
Oh,yeah!!!
Oh,yeah!!!
Oh,yeah!!!
Oh,yeah!!!
Oh,yeah!!!

Process finished with exit code 0

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

python定时利用QQ邮件发送天气预报的实例

python定时利用QQ邮件发送天气预报的实例

大致介绍 好久没有写博客了,正好今天有时间把前几天写的利用python定时发送QQ邮件记录一下 1、首先利用request库去请求数据,天气预报使用的是和风天气的API(www.hewe...

Python中将两个或多个list合成一个list的方法小结

python中,list这种数据结构很常用到,如果两个或者多个list结构相同,内容类型相同,我们通常会将两个或者多个list合并成一个,这样我们再循环遍历的时候就可以一次性处理掉了。所...

Java实现的执行python脚本工具类示例【使用jython.jar】

本文实例讲述了Java实现的执行python脚本工具类。分享给大家供大家参考,具体如下: 这里java中执行python脚本工具类,需要使用jython.jar java中执行pytho...

python pandas库中DataFrame对行和列的操作实例讲解

用pandas中的DataFrame时选取行或列: import numpy as np import pandas as pd from pandas import Sereis,...

python使用matplotlib绘制雷达图

python使用matplotlib绘制雷达图

本文实例为大家分享了python使用matplotlib绘制雷达图的具体代码,供大家参考,具体内容如下 示例代码: # encoding: utf-8 import pandas...