python3 多線程的基本用法,python3多線程用法

來源:互聯網
上載者:User

python3 多線程的基本用法,python3多線程用法

#coding=utf-8import threading #匯入threading包from time import sleepimport timedef task1():     print ("Task 1 executed." )    sleep(1)def task2():    print ("Task 2 executed." )    sleep(5)    print("多線程:")starttime=time.time(); #記錄開始時間threads = [] #建立一個線程列表,用於存放需要執行的子線程t1 = threading.Thread(target=task1) #建立第一個子線程,子線程的任務是調用task1函數,注意函數名後不能有()threads.append(t1)#將這個子線程添加到線程列表中t2 = threading.Thread(target=task2)#建立第二個子線程threads.append(t2)#將這個子線程添加到線程列表中for t in threads: #遍曆線程列表    t.setDaemon(True) #將線程聲明為守護線程,必須在start() 方法調用之前設定,如果不設定為守護線程程式會被無限掛起    t.start() #啟動子線程endtime=time.time();#記錄程式結束時間totaltime=endtime-starttime;#計算程式執行耗時print ("耗時:{0:.5f}秒" .format(totaltime)); #格式輸出耗時print('---------------------------')#以下為普通的單線程執行過程,不需解釋print("單線程:")starttime=time.time();task1();task2();endtime=time.time();totaltime=endtime-starttime;print ("耗時:{0:.5f}秒" .format(totaltime));


結果:


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.