python例题求乘客等车时间_Python多线程经典问题之乘客做公交车算法实例

本文实例讲述了Python多线程经典问题之乘客做公交车算法。分享给大家供大家参考,具体如下:

问题描述:

乘客乘坐公交车问题,司机,乘客,售票员协同工作,通过多线程模拟三者的工作。

司机:开车,停车

售票员:打开车门,关闭车门

乘客:上车,下车

用Python的Event做线程同步通信,代码如下:

# *-* coding:gb2312 *-*

import threading

import time

stationName=("车站0","车站1","车站2","车站3","车站4","车站5","车站6")

currentStationIndex = -1

eventBusStop = threading.Event()

eventClosedDoor = threading.Event()

eventOpenedDoor = threading.Event()

stationCount = len(stationName)

class Passenger(threading.Thread):

def __init__(self,no,getonStation,getoffStation):

self.no =no

self.getonStation=getonStation

self.getoffStation=getoffStation

threading.Thread.__init__(self)

def run(self):

bExit= False

global currentStationIndex

global stationCount

bAlreadyGetOnStation = False

while not bExit:

eventOpenedDoor.wait()

if self.getonStation == currentStationIndex and bAlreadyGetOnStation == False:

print "乘客%d在%s上车" %(self.no,stationName[currentStationIndex])

bAlreadyGetOnStation =True

elif self.getoffStation == currentStationIndex:

print "乘客%d在%s下车" %(self.no,stationName[currentStationIndex])

bExit = True

time.sleep(1)

class Driver(threading.Thread):

def run(self):

bExit= False

global currentStationIndex

global stationCount

while not bExit:

print "司机: 公交车开始行驶....."

time.sleep(5)

currentStationIndex += 1

print "司机: 到站 ",stationName[currentStationIndex]

eventBusStop.set()

eventClosedDoor.wait()

eventClosedDoor.clear()

if currentStationIndex == stationCount-1:

bExit= True

class Conductor(threading.Thread):

def run(self):

bExit= False

global currentStationIndex

global stationCount

while not bExit:

eventBusStop.wait()

eventBusStop.clear()

print "售票员打开车门:%s到了" %(stationName[currentStationIndex])

eventOpenedDoor.set()

time.sleep(5)

print "售票员关闭车门"

eventOpenedDoor.clear()

eventClosedDoor.set()

if currentStationIndex == stationCount-1:

bExit = True

def test():

passPool=[]

passPool.append(Passenger(0,3))

passPool.append(Passenger(1,1,3))

passPool.append(Passenger(2,2,4))

passPool.append(Passenger(3,5))

passPool.append(Passenger(4,3))

passPool.append(Passenger(5,4))

passPool.append(Passenger(6,4,5))

passPool.append(Passenger(7,2))

passPool.append(Passenger(8,3))

passPool.append(Conductor())

passPool.append(Driver())

leng = len(passPool)

for i in range(leng):

passPool[i].start()

if __name__=='__main__':

test()

输出结果如下:

15059833321.jpg?201722211588

希望本文所述对大家Python程序设计有所帮助。

总结

如果觉得编程之家网站内容还不错,欢迎将编程之家网站推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。

如您喜欢交流学习经验,点击链接加入交流1群:1065694478(已满)交流2群:163560250

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值