Python多线程的两种实现方式
生活随笔
收集整理的這篇文章主要介紹了
Python多线程的两种实现方式
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
Python的標準庫提供了兩個模塊:_thread和threading,_thread是低級模塊,threading是高級模塊,對_thread進行了封裝。絕大多數情況下,我們只需要使用threading這個高級模塊。
方式一:把一個函數傳入并創建Thread實例,然后調用start()開始執行
import threading def loop():for i in range(30):print(threading.current_thread().name + " --- " + str(i))threadA = threading.Thread(target=loop, name="線程A") threadB = threading.Thread(target=loop, name="線程B") threadA.start() threadB.start()執行結果部分截圖如下:
方式二:定義一個類,繼承自 threading.Thread類,使用 init(self) 方法進行初始化,在 run(self) 方法中寫上該線程要執行的程序,然后調用 start() 方法執行
執行結果部分截圖如下:
可以看到,輸出結果中,線程 A、B 的順序是混在一起的。
總結
以上是生活随笔為你收集整理的Python多线程的两种实现方式的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Python基础教程:回调在编程中的含义
- 下一篇: Python小技巧:用 print()