Python使用面向对象方式创建线程实现12306售票系统

WBOY
Release: 2016-06-10 15:07:01
Original
1540 people have browsed it

目前python 提供了几种多线程实现方式 thread,threading,multithreading ,其中thread模块比较底层,而threading模块是对thread做了一些包装,可以更加方便的被使用。

面向对象技术简介

类(Class): 用来描述具有相同的属性和方法的对象的集合。它定义了该集合中每个对象所共有的属性和方法。对象是类的实例。

类变量:类变量在整个实例化的对象中是公用的。类变量定义在类中且在函数体之外。类变量通常不作为实例变量使用。

数据成员:类变量或者实例变量用于处理类及其实例对象的相关的数据。

方法重写:如果从父类继承的方法不能满足子类的需求,可以对其进行改写,这个过程叫方法的覆盖(override),也称为方法的重写。

实例变量:定义在方法中的变量,只作用于当前实例的类。

继承:即一个派生类(derived class)继承基类(base class)的字段和方法。继承也允许把一个派生类的对象作为一个基类对象对待。例如,有这样一个设计:一个Dog类型的对象派生自Animal类,这是模拟"是一个(is-a)"关系(例图,Dog是一个Animal)。

实例化:创建一个类的实例,类的具体对象。

方法:类中定义的函数。

对象:通过类定义的数据结构实例。对象包括两个数据成员(类变量和实例变量)和方法。

---恢复内容开始---

通过面向对象的方法实现多线程,其核心是继承threading.Thread类。我们自己定义了一个类BoothThread, 这个类继承自thread.Threading类,通过修改Thread类的run()方法来定义线程所要执行的命令。

import threading # Python主要通过标准库中的threading包来实现多线程 import time import os #作为间隔 每次调用间隔.s def doChore(): time.sleep(.) # 定义一个类BoothThread继承自thread.Threading类 class BoothThread(threading.Thread): def __init__(self, tid, monitor): self.tid = tid self.monitor = monitor threading.Thread.__init__(self) def run(self): while True: monitor['lock'].acquire() # 调用lock.acquire() 加锁 if monitor['tick'] != : monitor['tick'] = monitor['tick'] - # 售票 售出一张减少一张 print(self.tid,':now left:',monitor['tick']) # 剩下的票数 doChore() else: print("Thread_id",self.tid," No more tickets") os._exit() # 票售完 退出程序 monitor['lock'].release() # 释放锁 doChore() monitor = {'tick':, 'lock':threading.Lock()} # 初始化票数 # 总共设置了个线程 for k in range(): new_thread = BoothThread(k, monitor) # 创建线程; Python使用threading.Thread对象来代表线程 类BoothThread继承自thread.Threading类 new_thread.start() # 调用start()方法启动线程
Copy after login

这里使用了一个词典 monitor存放全局变量,然后把词典作为参数传递给线程函数。由于词典是可变数据对象,所以当它被传递给函数的时候,函数所使用的依然是同一个对象,相当于被多个线程所共享。

以上内容给大家介绍了Python使用面向对象方式创建线程实现12306售票系统的全部叙述,希望大家喜欢。

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!