使用threading模块的Thread类来创建线程,介绍常用的三种方法:
1.创建一个Thread类的实例,传入一个函数
#coding=utf-8
import threading, time
loops=[4,2]
def func(index, sec):
print "func starts:%d"%(index)+" %s\n"%(time.ctime())
time.sleep(sec)
print "func ends:%d"%(index)+" %s\n"%(time.ctime())
def main():
threads =[]
nloop = range(nlen(loops))
for i in nloop:
tt = threading.Thread(target=func, args=(i, loops[i]))
print "the name of the threadind:%s\n"%(tt.getName())
threads.append(tt)
for i in nloop:
threads[i].start()
for i in nloop:
threads[i].join() #允许主线程等待所有的线程运行完之后在执行后面的逻辑
print "all done:%s\n"%(time.ctime())
if __name__ == "__main__":
main()
2.创建一个Thread类实例,传入以个可调用的类对象
#coding=utf-8
import time, threading
loops=[4,2]
class MyThread(object):
def __init__(self, func, args,name=""):
self.args = args
self.func = func
self.name = name
def __call__(self, *args, **kwargs):
self.func(*self.args)
def loop(nloop, nsec):
print "loop starts:%d"%(nloop) + " %s\n"%(time.ctime())
time.sleep(nsec)
print "loop ends:%d"%(nloop) + " %s\n"%(time.ctime())
def main():
threads =[]
for i in range(len(loops)):
tt = threading.Thread(target=MyThread(loop, (i,loops[i]),loop.__name__)) #仅修改了这里
print "线程名字:",tt.getName()
threads.append(tt)
for i in range(len(loops)):
threads[i].start()
for item in threads:
item.join()
print "all done:%s\n"%(time.ctime())
if __name__ == "__main__":
main()
3.子类化Thread类,创建一个子类的实例
#coding=utf-8
import threading,time
loops=[4,2]
class MyThread(threading.Thread):
def __init__(self,index, sec):
threading.Thread.__init__(self)
self.index = index
self.sec = sec
def run(self):
print "loop starts:%d"%(self.index) + " %s\n"%(time.ctime())
time.sleep(self.sec)
print "loop ends:%d"%(self.sec) + " %s\n"%(time.ctime())
def main():
nloop = range(len(loops))
threads = []
for i in nloop:
tt = MyThread(i,loops[i])
print "线程名字:",tt.getName()
threads.append(tt)
for i in range(len(loops)):
threads[i].start()
for item in threads:
item.join()
print "all done:%s\n"%(time.ctime())
if __name__ == "__main__":
main()