Python3 多線程示例

'''
多線程:
     1. 通過多線程並行兩個函數,兩函數分別不停的打印當前時間,
     2. 通過打印的時間判斷兩函數是否並行運行
'''




import threading,time


def process_1(interval_time):

    while True :
        time.sleep(interval_time)       #因爲是while循環,所以通過time.sleep()來控制循環間隔,單位S。
        print('{}: 進程1'.format(time.strftime('%Y-%m-%d %H:%M:%S',time.localtime())))


def process_2(interval_time):

    while True :
        time.sleep(interval_time)
        print('{}: 進程2'.format(time.strftime('%Y-%m-%d %H:%M:%S',time.localtime())))


if __name__ == "__main__":

    #---------創建線程對象----
    threading_1 = threading.Thread(target=process_1, args=(0.5,))       #args內是傳遞給函數的參數,必須是可迭代對象,通常使用元組
    threading_2 = threading.Thread(target=process_2, args=(0.5,))

    #--------開啓線程-----
    threading_1.start()
    threading_2.start()
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章