多線程
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()