python多线程实现方式_python中实现多线程有几种方式?
我們都知道,代碼編程不是固定的東西,而是非常靈活的內容,根據不同的內容,我們可以拓展出很多條內容,最終目的還是為了可以實現結果,給大家舉例說明其中一個最常用的多線程吧~以及實現的幾種方式。
1. 用函數創建多線程
在Python3中,Python提供了一個內置模塊 threading.Thread,可以很方便地讓我們創建多線程。
舉個例子import?time
from?threading?import?Thread
#?自定義線程函數。
def?target(name="Python"):
for?i?in?range(2):
print("hello",?name)
time.sleep(1)
#?創建線程01,不指定參數
thread_01?=?Thread(target=target)
#?啟動線程01
thread_01.start()
#?創建線程02,指定參數,注意逗號
thread_02?=?Thread(target=target,?args=("MING",))
#?啟動線程02
thread_02.start()
可以看到輸出hello?Python
hello?MING
hello?Python
hello?MING
2.用類創建多線程
相比較函數而言,使用類創建線程,會比較麻煩一點。
首先,我們要自定義一個類,對于這個類有兩點要求,
l必須繼承 threading.Thread 這個父類;
l必須復寫 run 方法。
來看一下例子為了方便對比,run函數我復用上面的main。import?time
from?threading?import?Thread
class?MyThread(Thread):
def?__init__(self,?type="Python"):
#?注意:super().__init__()?必須寫
#?且最好寫在第一行
super().__init__()
self.type=type
def?run(self):
for?i?in?range(2):
print("hello",?self.type)
time.sleep(1)
if?__name__?==?'__main__':
#?創建線程01,不指定參數
thread_01?=?MyT
hread()
#?創建線程02,指定參數
thread_02?=?MyThread("MING")
thread_01.start()
thread_02.start()
當然結果也是一樣的。hello?Python
hello?MING
hello?Python
hello?MING
3.線程對象的方法
上面介紹了當前 Python 中創建線程兩種主要方法。#?如上所述,創建一個線程
t=Thread(target=func)
#?啟動子線程
t.start()
#?阻塞子線程,待子線程結束后,再往下執行
t.join()
#?判斷線程是否在執行狀態,在執行返回True,否則返回False
t.is_alive()
t.isAlive()
#?設置線程是否隨主線程退出而退出,默認為False
t.daemon?=?True
t.daemon?=?False
#?設置線程名
t.name?=?"My-Thread"
至此,Python線程基礎知識,我們大概都介紹完了。感興趣的小伙伴可以多瀏覽看下內容哦~如果還想知道更多的python知識,可以到python學習網進行查詢。
創作挑戰賽新人創作獎勵來咯,堅持創作打卡瓜分現金大獎總結
以上是生活随笔為你收集整理的python多线程实现方式_python中实现多线程有几种方式?的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 用python配置文件_使用。Pytho
- 下一篇: LeetCode 113. 路径总和 I