多線程與雙端隊列結合使用,實現持久化任務(2)

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




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章