'''
def __init__(self,lock=None)
def acquire(self,blocking = True ,timeout = -1)
def wait(self,timeout = None)
def notify(self,n=1) 唤醒一个等待线程对象
def notify_all(self) 唤醒所有等待的线程
'''
import threading
import time
class msg:
def __init__(self, condition):
self.__title = None
self.__content = None
self.__condition = condition
self.__flag = True
def set_info(self, title, content):
self.__condition.acquire()
if self.__flag == False:
self.__condition.wait()
self.__title = title
time.sleep(1)
self.__content = content
print('%s title =%s content = %s' % (threading.current_thread().name, self.__title, self.__content))
self.__flag = False
self.__condition.notify()
self.__condition.release()
def __str__(self):
self.__condition.acquire()
if self.__flag == True:
self.__condition.wait()
try:
time.sleep(0.8)
return '%s title =%s content = %s' % (threading.current_thread().name, self.__title, self.__content)
finally:
self.__flag=True
self.__condition.notify()
self.__condition.release()
def producer_handle(message):
for num in range(50):
if num %2 ==0:
message.set_info('chenxianq','测试工程师')
else:
message.set_info('tencent','www.tencent.com')
def consumer_handle(message):
for num in range(50):
print(message)
def main():
condition =threading.Condition()
message = msg(condition)
producter_thred = threading.Thread(target=producer_handle,name='生产线程',args=(message,))
consumer_thred = threading.Thread(target=consumer_handle,name='消费线程',args=(message,))
producter_thred.start()
consumer_thred.start()
if __name__ == '__main__':
main()
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 使用C#创建一个MCP客户端
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列1:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现