python线程编写的两种方法
Python中如果要使用线程的话,python的lib中提供了两种方式。一种是函数式,一种是用类来包装的线程对象。举两个简单的例子希望起到抛砖引玉的作用,关于多线程编程的其他知识例如互斥、信号量、临界区等请参考python的文档及相关资料。
1、调用thread模块中的start_new_thread()函数来产生新的线程,请看代码:
python代码
###thread_example.py
importtime
importthread
deftimer(no,interval):#自己写的线程函数
whileTrue:
print'Thread:(%d)Time:%s'%(no,time.ctime())
time.sleep(interval)
deftest():#使用thread.start_new_thread()来产生2个新的线程
thread.start_new_thread(timer,(1,1))
thread.start_new_thread(timer,(2,3))
if__name__=='__main__':
test()
这个是thread.start_new_thread(function,args[,kwargs])函数原型,其中function参数是你将要调用的线程函数;args是讲传递给你的线程函数的参数,他必须是个tuple类型;而kwargs是可选的参数。
线程的结束一般依靠线程函数的自然结束;也可以在线程函数中调用thread.exit(),他抛出SystemExitexception,达到退出线程的目的。
2、通过调用threading模块继承threading.Thread类来包装一个线程对象。请看代码:
python代码
importthreading
importtime
classtimer(threading.Thread):#我的timer类继承自threading.Thread类
def__init__(self,no,interval):
#在我重写__init__方法的时候要记得调用基类的__init__方法
threading.Thread.__init__(self)
self.no=no
self.interval=interval
defrun(self):#重写run()方法,把自己的线程函数的代码放到这里
whileTrue:
print'ThreadObject(%d),Time:%s'%(self.no,time.ctime())
time.sleep(self.interval)
deftest():
threadone=timer(1,1)#产生2个线程对象
threadtwo=timer(2,3)
threadone.start()#通过调用线程对象的.start()方法来激活线程
threadtwo.start()
if__name__=='__main__':
test()
其实thread和threading的模块中还包含了其他的很多关于多线程编程的东西,例如锁、定时器、获得激活线程列表等等。
以上内容为大家介绍了python中的反斜杠,希望对大家有所帮助,如果想要了解更多Python相关知识,请关注IT培训机构:千锋教育。http://www.mobiletrain.org/

相关推荐HOT
更多>>
编写一个简单的游戏来学习 Python
通过编写一个“猜数字”游戏来探索Python(和其他编程语言)。在这个系列中,我们要用不同的编程语言编写相同的应用,以比较各种语言是如何工作的...详情>>
2023-11-11 23:31:59
新手学Python用什么编辑器比较好?
工欲善其事必先利其器,选好工具学习更高效。市面上流行的编辑器众多,根据自己的需求选择适合自己。p小白可以选择pycharm配置简单功能强大使用...详情>>
2023-11-11 22:54:28
Python 中 Logging 模块使用详情
1.为什么要用logging模块在实际应用中,日志文件十分重要,通过日志文件,我们知道程序运行的细节;同时,当程序出问题时,我们也可以通过日志快...详情>>
2023-11-11 21:59:42
python学习进阶方法
阶段一:前辈领进门。第一眼是一个前辈给我看了看Python的代码,因为自己最早学习的是Java语言,第一眼看到Python的时候,前辈说,“Python是面...详情>>
2023-11-11 20:20:18热门推荐
技术干货






