模拟售票系统

本文介绍了一个使用Python多线程实现的模拟售票系统。该系统包含Buyer和Computer两个类,Buyer用于模拟购票者,Computer用于模拟售票计算机。通过多线程技术,模拟了多个购票者同时请求购票的情况,并使用锁(lock)机制确保票数的正确更新。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

以下是模拟系统的代码:
 

import threading
import time
import random
class buyer(object):
    def __init__(self,name='',number=1):
        self.name = name
        self.number = number
lock = threading.Lock()
class computer(object):
    def __init__(self,count=0):
        self.count = count

    def query_with_buyer_info(self,other):
        print('正在为{}查询剩余票数'.format(other.name))
        time.sleep(random.randint(1,3))
        lock.acquire()
        if self.count >= other.number:
            print('有票,{}可以购买'.format(other.name))
            time.sleep(random.randint(1,3))
            self.count -= other.number
        else:
            print('你所购买的票已售空')
        lock.release()
hanmeimei = buyer('韩梅梅',2)
houzi = buyer(' 猴子',5)

com = computer(7)
thread1 = threading.Thread(target=com.query_with_buyer_info,name='thread1',args=(hanmeimei,))
thread2 = threading.Thread(target=com.query_with_buyer_info,name='thread2',args=(houzi,))

thread1.start()
thread2.start()

仅供参考

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值