Python簡單使用多線程

Python簡單使用多線程

利用多線程同時執行3次函數,分別使用sleep去添加延時時間,觀察程序最後執行結束的時間

# -*- coding:utf-8 -*-
import threading
import datetime
import time

locks = None


def unit_test(sleep):
    """
    多線程單元測試
    :param sleep: 等待的時間
    :return:
    """
    # locks.acquire()   獲取鎖 -- 獲取鎖之後,其他的線程在此等待
    print('start loop {}, '.format(sleep), datetime.datetime.now())
    time.sleep(sleep)
    print('loop {} down, '.format(sleep), datetime.datetime.now())
    # locks.release()   釋放鎖 -- 如果不釋放鎖,後續的線程會一直被阻塞不能進入


def thread_run(sleep_list):
    """
    運行多線程
    :param sleep_list: 延時時間列表
    :return:
    """
    global locks
    locks = threading.Lock()
    threads = []
    start_time = datetime.datetime.now()

    # insert all threads to threads list
    for i in sleep_list:
        t = threading.Thread(target=unit_test, args=(i,))
        threads.append(t)

    # start all threads
    for thread in threads:
        thread.start()

    # waiting all thread close
    for thread in threads:
        thread.join()

    end_time = datetime.datetime.now()
    print('所有線程結束,一共消耗{}秒鐘'.format((end_time - start_time).seconds))


def main():
    sleep_list = [2, 4, 1]
    thread_run(sleep_list=sleep_list)


if __name__ == '__main__':
    main()

執行結果:

start loop 2,  2020-01-15 16:53:48.156806
start loop 4,  2020-01-15 16:53:48.156806
start loop 1,  2020-01-15 16:53:48.157804
loop 1 down,  2020-01-15 16:53:49.158589
loop 2 down,  2020-01-15 16:53:50.157596
loop 4 down,  2020-01-15 16:53:52.158573
所有線程結束,一共消耗4秒鐘

從執行時間可以看出,程序在調用的時候是同時執行的,sleep最大值爲4秒,程序總共運行時間也只花費了4秒。

發佈了27 篇原創文章 · 獲贊 16 · 訪問量 2855
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章