多线程模块

多线程模块
Python的多线程模块有两种实现方法
函数,线程类
一【函数】
调用thread模块中的start_new_thread()函数来创建线程,以线程函数的形式告诉线程该做什么

#!/usr/bin/python
import thread
def f(name):
	print "this is "+name
if __name__=="__main__":
	thread.start_new_thread(f,("mimi",))
	while 1:
		pass

二【线程类】
调用threading模块,创建threading.Thread的子类来得到自定义线程类

[root@server0 thread]# cat 2.py 
#!/usr/bin/python
import threading
class Th(threading.Thread):
	def __init__(self,name):
		threading.Thread.__init__(self)
		self.t_name=name
	def run(self): 重写run函数,线程默认从此函数开始执行
		print "this is "+self.t_name
if __name__=="__main__":
	thread1=Th("thread1")
	thread1.start() start()函数启动线程,自动执行run函数
	#thread1.join() 
	print "main thread is over

threading.Thread类的可继承函数;
getName()获得线程对象名称
setName()设置线程对象名称
Join()等待调用的线程结束之后再运行之后的命令

三【线程锁】

Threading提供线程锁,可实现线程同步

#!/usr/bin/python
import time
import threading
class Th(threading.Thread):
	def __init__(self,thread_name):
		threading.Thread.__init__(self)
		self.setName(thread_name)
	def run(self):
		threadLock.acquire()   获得锁以后再运行
		print  "this is thread"+self.getName()
		for i in range(3):
			time.sleep(1)
			print str(i)
		print self.getName()+"is over"
		threadLock.release()释放锁
if __name__=="__main__":
	threadLock=threading.Lock()
	thread1=Th("Thread1")
	thread2=Th("Thread2")
	thread1.start()
	thread2.start()
posted @ 2016-07-26 17:07  夏日花开  阅读(190)  评论(0编辑  收藏  举报