Python線程之多線程展示詳解
什么多線程?
多線程,就是多個獨立的運行單位,同時執(zhí)行同樣的事情。
想想一下,文章發(fā)布后同時被很多讀者閱讀,這些讀者在做的事情‘閱讀'就是一個一個的線程。
多線程就是多個讀者同時閱讀這篇文章。重點是:同時有多個讀者在做閱讀這件事情。
如果是多個讀者,分時間閱讀,最后任意時刻只有一個讀者在閱讀,雖然是多個讀者,但還是單線程。
我們再拿前面分享的代碼:關注和點贊。
def dianzan_guanzhu():
now = datetime.datetime.now()
name = "python萌新"
print("%s name:%s" % (now, name))
time.sleep(1)
result = "好棒!" + name + " 關注雷學委,學會了開發(fā)知識!"
print("%s result:%s" % (now, result))
return result
我們看看下面的代碼:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2021/11/21 12:02 上午
# @Author : LeiXueWei
# @CSDN/Juejin/Wechat: 雷學委
# @XueWeiTag: CodingDemo
# @File : __init__.py.py
# @Project : hello
import threading
import datetime
import time
def dianzan_guanzhu():
now = datetime.datetime.now()
name = "python萌新"
print("%s name:%s" % (now, name))
time.sleep(1)
result = "好棒!" + name + " 關注雷學委,學會了開發(fā)知識!"
print("%s result:%s" % (now, result))
return result
for i in range(3):
mythread = threading.Thread(name="t-" + str(i), target=dianzan_guanzhu)
print("mythread:", mythread)
print("is_alive:", mythread.is_alive())
mythread.start()
print("is_alive:", mythread.is_alive())
Thread類可以傳入name指定線程名字。
直接復制運行,這里我們創(chuàng)建了3個線程。
它們依次調(diào)用了dianzan_guanzhu函數(shù)
下面是運行結(jié)果:

這3個線程不同時間打印完成了,但是內(nèi)容打印亂序了,甚至還串行了。
讀者同學可以多運行幾次。
獲取活躍線程相關數(shù)據(jù)
threading.active_count函數(shù): 可以獲取活躍線程數(shù)。threading.current_thread函數(shù):可以獲取活躍線程對象,這樣我們可以獲取這樣獲取線程名稱:threading.current_thread().getName()。
前文說過了,加上主線程,一共是4個線程。
運行下面代碼看看:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2021/11/21 12:02 上午
# @Author : LeiXueWei
# @CSDN/Juejin/Wechat: 雷學委
# @XueWeiTag: CodingDemo
# @File : __init__.py.py
# @Project : hello
import random
import threading
import datetime
import time
def dianzan_guanzhu():
thread_name = threading.current_thread().getName()
now = datetime.datetime.now()
print("線程啟動了:", thread_name)
name = "python萌新"+thread_name
print("%s - %s name:%s" % (thread_name, now, name))
time.sleep(1)
result = "好棒!" + name + " 關注雷學委,學會了開發(fā)知識!"
print("%s - %s result:%s" % (thread_name, now, result))
return result
for i in range(3):
mythread = threading.Thread(name="t-" + str(i), target=dianzan_guanzhu)
print("mythread:", mythread)
print("is_alive:", mythread.is_alive())
mythread.start()
ac = threading.active_count()
print("active_count:", ac)
如果我們把活躍線程數(shù)打印,那么等3個線程都start調(diào)用了。
加上主線程,最多是4個活躍線程。

今天先展示一下多個線程執(zhí)行同個任務的代碼實現(xiàn)。
總結(jié)
本篇文章就到這里了,希望能夠給你帶來幫助,也希望您能夠多多關注腳本之家的更多內(nèi)容!
相關文章
python矩陣的轉(zhuǎn)置和逆轉(zhuǎn)實例
今天小編就為大家分享一篇python矩陣的轉(zhuǎn)置和逆轉(zhuǎn)實例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-12-12
python 基于空間相似度的K-means軌跡聚類的實現(xiàn)
這篇文章主要介紹了python 基于空間相似度的K-means軌跡聚類的實現(xiàn),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2021-03-03

