zoukankan      html  css  js  c++  java
  • ★ Contidion wait+notify方法

      在调用 with cond 之后才能调用wait和notify方法
    在condition 里面有两层锁,一把锁会在线程调用wait方法的时候释放,上面的锁会在每次调用wait的时候分配一把并
    放入cond中的等待队列中,知道notify方法唤醒




    此处唤醒的进程时随机!!!

    聊天尝试对两个进程互相切换的实现

     1 import threading
     2 
     3 from threading import Condition
     4 
     5 class ZhangSan(threading.Thread):
     6     def __init__(self,cond):
     7         super().__init__(name='张三')
     8         self.cond=cond
     9 
    10     def run(self):
    11         with self.cond:
    12             print("{}:你好".format(self.name))        #1
    13             self.cond.notify()
    14             self.cond.wait()
    15 
    16             print("{}:lalala".format(self.name))
    17             self.cond.notify()
    18             self.cond.wait()
    19 
    20 
    21 class LiSi(threading.Thread):
    22     def __init__(self,cond):
    23         super().__init__(name='李四')
    24         self.cond = cond
    25     def run(self):
    26         with self.cond:
    27             self.cond.wait()            #关键
    28             print("{}:你好".format(self.name))
    29             self.cond.notify()
    30 
    31             self.cond.wait()
    32             print("{}:滚犊子".format(self.name))
    33             self.cond.notify()
    34             # print("{}:滚犊子".format(self.name))
    35 
    36 
    37 if __name__ == '__main__':
    38     cond = threading.Condition()
    39     zhangsan = ZhangSan(cond)
    40     lisi = LiSi(cond)
    41 
    42     #   程序的执行顺序
    43     lisi.start()
    44     zhangsan.start()
  • 相关阅读:
    Python LED
    vmvare虚拟机经验
    Debian系统简要说明
    Android onclick监听事件打开新界面
    在国外搭个人服务器(顺便访问外网)
    生成指定时间内的 随机日起
    生成指定时间内的日期
    Mac 上查找javahome
    java 学习的网站
    Java 线程
  • 原文地址:https://www.cnblogs.com/sdosun/p/13222417.html
Copyright © 2011-2022 走看看