python 多線程執行腳本

多線程執行:eg.

"""
    多線程執行
"""
import datetime
from time import sleep
import threading
import sys, getopt

class Test(threading.Thread):

    # TODO 初始化參數
    def __init__(self, times):
        threading.Thread.__init__(self)
        self.times = times

    # TODO 邏輯代碼
    def run(self):
        print('time is %s start: %s' % (self.times, str(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'))))
        sleep(3)
        print('time is %s start: %s' % (self.times, str(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'))))
        sleep(3)


    # TODO 資源回收
    def __del__(self):
        print('over %s' % self.times)

def run():
    mythreads = []
    # 線程數設置
    lites = 20
    # 創建多線程
    for item in range(lites):
        try:
            task_item = Test(item)
            task_item.start()
            mythreads.append(task_item)
        except:
            raise

    for thread in mythreads:
        thread.join()

if __name__ == '__main__':
    run()

 

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