多线程
import threading
import time
from time import sleep
def now_time():
return str(time.strftime("%Y-%m-%d %H-%M-%S",time.localtime()))
def func(loop,sec):
print "start loop ",loop," at ",now_time()
sleep(sec)
print "loop ",loop," done at:",now_time()
def thread_func():
print "starting at:",now_time()
thread_pool = []
for i in xrange(10):
th = threading.Thread(target=func,args=(i,2))
thread_pool.append(th)
for th in thread_pool:
th.start()
for th in thread_pool:
threading.Thread.join(th)
print "all done at:",now_time()
if __name__ == '__main__':
thread_func()
<pre name="code" class="python">继承线程类
import threading
import time
from time import sleep,ctime
def now_time():
return str(time.strftime("%Y-%m-%d %H-%M-%S",time.localtime()))
class MyThread(threading.Thread):#继承线程类
def __init__(self,nloop,nsec):
super(MyThread,self).__init__()
self.nloop = nloop
self.nsec =nsec
def run(self):
print "start loop:",self.nloop,"at:",ctime()
sleep(self.nsec)
print "loop",self.nloop,"done at:",ctime()
def main():
thread_pool=[]
print "start at:",now_time()
for i in xrange(10):
thread_pool.append(MyThread(i,2))
for item in thread_pool:
item.start()
for item in thread_pool:
item.join()
print "all done at:",now_time()
if __name__ == '__main__':
main()
更多资料 · 微信公众号搜索【CTO Plus】关注后,获取更多,我们一起学习交流。
关于公众号的描述访问如下链接