您的位置:首页 > 编程语言 > Python开发

[Python]多线程--threading模块实现

2013-04-02 17:41 701 查看
#!/usr/bin/env python
#coding=utf-8
#来源: python核心编程 多线程章节

import threading
from time import ctime,sleep,time

'''
使用建立实例的方法使用threading的多线程方法,建立2个线程,熟悉线程的基本操作
'''
'''
#创建一个thread实例,传给他一个函数
secds=[4,2] #每个线程停顿的时间

def loop(nloop,secds):
print 'the loop',nloop,'started',ctime()
sleep(secds)
print 'the loop',nloop,'stoped',ctime()

#main
def main():
print 'mian thread started ',ctime()
threads=[]
nloops=range(len(secds))
#创建所有线程的实例
for i in nloops:
threadins=threading.Thread(target=loop,args=(i,secds[i])) #这里的target等参数不能省略
threads.append(threadins)
#依次启动所有子线程
for i in nloops:
threads[i].start()
#等待所有线程结束
for i in nloops:
threads[i].join()
print 'all threads done ',ctime()

if __name__=='__main__':
main()
'''

#创建一个Thread,传给他一个可调用类的对象,这次是把方法变成对象传入,很少见到这么用,测试有点问题
#程序是能跑了 但是这个d到底是什么还是没搞明白
'''
secds=[1,5]

#子线程对应的类
class ThreadFun(object):
def __init__(self,args):
self.args = args

def __call__(self):          #自动调用
apply(self.loop,self.args)

def loop(d,nloop,nsec):   #这种调用方法 这里会多加一个参数
#print dir(d)
#print tpye(d)   #tpye not defined  !!
print '\-'*20
print 'loop',nloop,'start',ctime()
sleep(nsec)
print 'loop',nloop,'stop',ctime()

def main():
print 'start :',ctime()
threads=[]
nloops = range(len(secds))

for i in nloops:
t=threading.Thread(target=ThreadFun((i,secds[i])))
threads.append(t)

for i in nloops:
threads[i].start() #start all threads

for i in nloops:
threads[i].join() #wait for all threads done

print 'all thread done' ,ctime()

if __name__=='__main__':
main()
'''

#下面是我们最常用的一个方法,就是继承类实现多线程
#这个是引用tutorialspoint的代码
exitFlag = 0

class myThread (threading.Thread):   #继承threading.Thread
def __init__(self, threadID, name, counter):
threading.Thread.__init__(self)
self.threadID = threadID
self.name = name
self.counter = counter
def run(self):
print "Starting " + self.name
print_time(self.name, self.counter, 6)  #循环6次,每次执行了得线程都要打印一次
print "Exiting " + self.name

def print_time(threadName, delay, counter):
while counter:
if exitFlag:
thread.exit()
sleep(delay)
print "%s: %s" % (threadName, ctime(time()))
counter -= 1

# Create new threads
thread1 = myThread(1, "Thread-1", 1)
thread2 = myThread(2, "Thread-2", 2)

# Start new Threads
thread1.start()
thread2.start()

print "Exiting Main Thread"

#还有一个常用的模块就是Queue
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息