python多線程(一)

來源:互聯網
上載者:User

標籤:coding   mon   傳參   自動   自訂   調用   判斷   format   ini   

---恢複內容開始---

首先先來看個單線程的例子:

from time import ctime,sleepdef music():    for i in range(2):        print("I was listening to music. %s" %ctime())        sleep(1)def move():    for i in range(2):        print("I was at the movies! %s" %ctime())        sleep(5)if __name__ == ‘__main__‘:    music()    move()    print("all over %s" %ctime())

首先先聽了一首music,覺得音樂好聽,就用for迴圈來控制音樂的播放了兩次,每首音樂播放需要1秒鐘,sleep()來控制音樂播放的時間長度,

聽說有部電影好看,我們就去看,每一場電影需要5秒鐘,電影是在太好看了,我們有for迴圈2次運行結果如下:

我正在聽音樂. Sun May 20 12:15:52 2018我正在聽音樂. Sun May 20 12:15:53 2018你正在看抖音! Sun May 20 12:15:54 2018你正在看抖音! Sun May 20 12:15:59 2018all over Sun May 20 12:16:04 2018[Finished in 12.2s]

通過上邊我們看到有兩個方法,想到我們可不可以自訂聽什麼歌,看抖音什麼類型的短視頻

於是對上面代碼加以改造:

from time import ctime,sleep

def music(song):
for i in range(2):
print("我正在聽%s音樂. %s" %(song,ctime()))
sleep(1)

def move(tv):
for i in range(2):
print("你正在看抖音%s短視頻! %s" %(tv,ctime()))
sleep(5)

if __name__ == ‘__main__‘:
music(‘紙短情長‘)
move(‘吃雞‘)
print("all over %s" %ctime())

看到了吧 我們加了個參數,運行結果:

我正在聽紙短情長音樂. Sun May 20 12:21:24 2018我正在聽紙短情長音樂. Sun May 20 12:21:25 2018你正在看抖音吃雞短視頻! Sun May 20 12:21:26 2018你正在看抖音吃雞短視頻! Sun May 20 12:21:31 2018all over Sun May 20 12:21:36 2018[Finished in 12.2s]

多線程:體現了一下單線程的使用,那麼我們就來看看多線程到底有什麼更加強大的功能

from time import ctime, sleepimport threadingdef music(song):    for i in range(2):        print("I was listening to %s. %s" % (song, ctime()))        sleep(1)def move(mymove):    for i in range(2):        print("I was at the %s! %s" % (mymove, ctime()))        sleep(5)threads = []th1 = threading.Thread(target=music, args=(‘一個人走‘,))threads.append(th1)th2 = threading.Thread(target=move, args=(‘複仇者聯盟‘,))threads.append(th2)if __name__ == ‘__main__‘:    for t in threads:        t.setDaemon(True)  # setDaemon(True)將線程聲明為        # 守護線程,必須在start() 方法調用之前設定,如果        # 不設定為守護線程程式會被無限掛起。子線程啟動後,        # 父線程也繼續執行下去,當父線程執行完最後一條語句        t.start()    t.join()#程式加了個join()方法,用於等待線程    # 終止。join()的作用是,在子線程完成運行之前,這個子線    # 程的父線程將一直被阻塞。    print("all over %s" % ctime())

首先肯定是要匯入threading模組:import threading

 

 

threads = []th1 = threading.Thread(target=music, args=(‘一個人走‘,))threads.append(th1)

  建立了threads數組,建立線程th1,使用threading.Thread()方法,在這個方法中調用music方法target=music,args方法對music進行傳參。 把建立好的線程t1裝到threads數組中。

  接著以同樣的方式建立線程th2,並把t2也裝到threads數組。

for t in threads:

  t.setDaemon(True)

  t.start()

最後通過for迴圈遍曆數組。(數組被裝載了t1和t2兩個線程)

 

setDaemon()

  setDaemon(True)將線程聲明為守護線程,必須在start() 方法調用之前設定,如果不設定為守護線程程式會被無限掛起。子線程啟動後,父線程也繼續執行下去,當父線程執行完最後一條語句print "all over %s" %ctime()後,沒有等待子線程,直接就退出了,同時子線程也一同結束。

 

start()

開始線程活動。

 運行結果:

I was listening to 一個人走. Sun May 20 12:26:33 2018I was at the 複仇者聯盟! Sun May 20 12:26:33 2018I was listening to 一個人走. Sun May 20 12:26:34 2018I was at the 複仇者聯盟! Sun May 20 12:26:38 2018all over Sun May 20 12:26:43 2018[Finished in 10.3s]

到這裡,我們發現如果我有好多個線程,那豈不是我每個線程都要建立一個th~

#!user/bin/env python# coding=utf-8from time import ctime, sleepimport threadingdef music(song):    for i in range(2):        print("I was listening to %s. %s" % (song, ctime()))        sleep(1)def move(mymove):    for i in range(2):        print("I was at the %s! %s" % (mymove, ctime()))        sleep(5)def new_threading(name):    new_thread = name.split(‘.‘)[1]    if new_thread == ‘mp3‘:        music(name)    else:        if new_thread == ‘mp4‘:            move(name)        else:            print(‘error:The format is not recognized!‘)list = [‘紙短情長.mp3‘, ‘複仇者聯盟.mp4‘]threads = []file_count = range(len(list))# 建立線程for i in file_count:    t = threading.Thread(target=new_threading, args=(list[i],))    threads.append(t)    # 啟動線程if __name__ == ‘__main__‘:    for t in file_count:        threads[t].start()    for t in file_count:        threads[t].join()    print("all over %s" % ctime())

 

我們增加了一個增加線程的方法,只要想 list中添加一個檔案,程式會自動為其建立線程

I was listening to 紙短情長.mp3. Sun May 20 12:40:10 2018I was at the 複仇者聯盟.mp4! Sun May 20 12:40:10 2018I was listening to 紙短情長.mp3. Sun May 20 12:40:11 2018I was at the 複仇者聯盟.mp4! Sun May 20 12:40:15 2018all over Sun May 20 12:40:20 2018[Finished in 10.2s]

 

是不是實現了 ,我們繼續最佳化,發現new——threading中有個判斷副檔名的,然後才調用music和move()

那為什麼不用一個方法(也就是一個軟體)同時播放音樂和電影呢

#!user/bin/env python# coding=utf-8from time import ctime, sleepimport threadingdef super_player(file_type,time):    for i in range(2):        print("現正播放 %s. %s" % (file_type, ctime()))        sleep(time)list ={‘紙短情長.mp3‘:2, ‘複仇者聯盟3.mp4‘:2,‘人民的名義.wav‘:4}threads = []file_count = range(len(list))# 建立線程for file_type,time in list.items():    t = threading.Thread(target=super_player, args=(file_type,time))    threads.append(t)    # 啟動線程if __name__ == ‘__main__‘:    for t in file_count:        # [t].setDaemon(True)  # setDaemon(True)將線程聲明為        # 守護線程,必須在start() 方法調用之前設定,如果        # 不設定為守護線程程式會被無限掛起。子線程啟動後,        # 父線程也繼續執行下去,當父線程執行完最後一條語句        threads[t].start()    for t in file_count:        threads[t].join()    # t.join()#只對上面的程式加了個join()方法,用於等待線程    # 終止。join()的作用是,在子線程完成運行之前,這個子線    # 程的父線程將一直被阻塞。    print("all over %s" % ctime())

這裡我們將list換成字典,定義播放的檔案和時間長度,通過字典的items()方法來迴圈的取file和time,取到的這兩個值用於建立線程。

建立super_player()函數,用於接收file和time,用於確定要播放的檔案及時間長度。運行結果如下:

現正播放 紙短情長.mp3. Sun May 20 12:52:30 2018現正播放 複仇者聯盟3.mp4. Sun May 20 12:52:30 2018現正播放 人民的名義.wav. Sun May 20 12:52:30 2018現正播放 紙短情長.mp3. Sun May 20 12:52:32 2018現正播放 複仇者聯盟3.mp4. Sun May 20 12:52:32 2018現正播放 人民的名義.wav. Sun May 20 12:52:34 2018all over Sun May 20 12:52:38 2018[Finished in 8.2s]

 

python多線程(一)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.