欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

python 實現(xiàn)多線程的三種方法總結

 更新時間:2021年04月24日 11:47:30   作者:淋巴不想動  
這篇文章主要介紹了python 實現(xiàn)多線程的三種方法總結,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧

1._thread.start_new_thread(了解)

import threading
import time
import _thread
def job():
    print("這是一個需要執(zhí)行的任務。。。。。")
    print("當前線程的個數(shù):", threading.active_count() )
    print("當前線程的信息:", threading.current_thread())
    time.sleep(100)
if __name__ == '__main__':
    # 創(chuàng)建多線程時, 需要制定該線程執(zhí)行的任務
    _thread.start_new_thread(job, ())
    _thread.start_new_thread(job, ())
    job()

2.threading.Thread

import threading
import time
def job():
    print("這是一個需要執(zhí)行的任務。。。。。")
    print("當前線程的個數(shù):", threading.active_count() )
    time.sleep(1)
    print("當前線程的信息:", threading.current_thread())
if __name__ == '__main__':
    # 創(chuàng)建多線程時, 需要制定該線程執(zhí)行的任務.name線程名字 target目標函數(shù)名
    t1 = threading.Thread(target=job,name='job1')
    t2 = threading.Thread(target=job,name='job2')
    t1.start()
    t2.start()
    print(threading.active_count())
 print("程序執(zhí)行結束.....")

輸出:

這是一個需要執(zhí)行的任務。。。。。

當前線程的個數(shù): 3

這是一個需要執(zhí)行的任務。。。。。

3

程序執(zhí)行結束.....

當前線程的個數(shù): 3

當前線程的信息: <Thread(job1, started 140416648140544)>

當前線程的信息: <Thread(job2, started 140416639747840)>

出現(xiàn)的問題: 主線程執(zhí)行結束, 但是子線程還在運行。

join()方法可以等待所有的子線程執(zhí)行結束之后, 再執(zhí)行主線程。

import threading
import time
def job():
    print("這是一個需要執(zhí)行的任務。。。。。")
    print("當前線程的個數(shù):", threading.active_count() )
    print("當前線程的信息:", threading.current_thread())
 time.sleep(1)
if __name__ == '__main__':
    # 創(chuàng)建多線程時, 需要制定該線程執(zhí)行的任務.name線程名字 target目標函數(shù)名
    t1 = threading.Thread(target=job,name='job1')
    t2 = threading.Thread(target=job,name='job2')
    t1.start()
    t2.start()
    print(threading.active_count())
    # 出現(xiàn)的問題: 主線程執(zhí)行結束, 但是子線程還在運行。
    # 等待所有的子線程執(zhí)行結束之后, 再執(zhí)行主線程
    t1.join()
    t2.join()
    print("程序執(zhí)行結束.....")

之前寫過一個簡單爬蟲的實驗,現(xiàn)在希望獲取十個ip的城市和國家

-不使用多線程

import time
from urllib.request import urlopen
# 記錄時間的裝飾器
def timeit(f):
    def wrapper(*args, **kwargs):
        start_time = time.time()
        res = f(*args, **kwargs)
        end_time = time.time()
        print("%s函數(shù)運行時間:%.2f" % (f.__name__, end_time - start_time))
        return res
    return wrapper
def get_addr(ip):
    url = "http://ip-api.com/json/%s" % (ip)
    urlObj = urlopen(url)
    # 服務端返回的頁面信息, 此處為字符串類型
    pageContent = urlObj.read().decode('utf-8')
    # 2. 處理Json數(shù)據(jù)
    import json
    # 解碼: 將json數(shù)據(jù)格式解碼為python可以識別的對象;
    dict_data = json.loads(pageContent)
    print("""
                        %s
    所在城市: %s
    所在國家: %s
    
    """ % (ip, dict_data['city'], dict_data['country']))
@timeit
def main():
    ips = ['12.13.14.%s' % (i + 1) for i in range(10)]
    for ip in ips:
        get_addr(ip)
if __name__ == '__main__':
    main()

時間需要138.91秒。

-使用多線程

import threading
import time
from urllib.request import urlopen
def timeit(f):
    def wrapper(*args, **kwargs):
        start_time = time.time()
        res = f(*args, **kwargs)
        end_time = time.time()
        print("%s函數(shù)運行時間:%.2f" % (f.__name__, end_time - start_time))
        return res
    return wrapper
def get_addr(ip):
    url = "http://ip-api.com/json/%s" % (ip)
    urlObj = urlopen(url)
    # 服務端返回的頁面信息, 此處為字符串類型
    pageContent = urlObj.read().decode('utf-8')
    # 2. 處理Json數(shù)據(jù)
    import json
    # 解碼: 將json數(shù)據(jù)格式解碼為python可以識別的對象;
    dict_data = json.loads(pageContent)
    print("""
                        %s
    所在城市: %s
    所在國家: %s
    
    """ % (ip, dict_data['city'], dict_data['country']))
@timeit
def main():
    ips = ['12.13.14.%s' % (i + 1) for i in range(10)]
    threads = []
    for ip in ips:
        # 實例化10個對象,target=目標函數(shù)名,args=目標函數(shù)參數(shù)(元組格式)
        t = threading.Thread(target=get_addr, args=(ip, ))
        threads.append(t)
        t.start()
    
    # 等待所有子線程結束再運行主線程
    [thread.join() for thread in threads]
if __name__ == '__main__':
    main()

3.重寫run方法

重寫run方法, 實現(xiàn)多線程, 因為start方法執(zhí)行時, 調(diào)用的是run方法;run方法里面編寫的內(nèi)容就是你要執(zhí)行的任務;

import threading
import time
# 重寫一個類,繼承于threading.Thread
class MyThread(threading.Thread):
    def __init__(self, jobName):
        super(MyThread, self).__init__()
        self.jobName = jobName
    # 重寫run方法, 實現(xiàn)多線程, 因為start方法執(zhí)行時, 調(diào)用的是run方法;
    # run方法里面編寫的內(nèi)容就是你要執(zhí)行的任務;
    def run(self):
        print("這是一個需要執(zhí)行的任務%s。。。。。" %(self.jobName))
        print("當前線程的個數(shù):", threading.active_count() )
        time.sleep(1)
        print("當前線程的信息:", threading.current_thread())
if __name__ == '__main__':
    t1 = MyThread("name1")
    t2 = MyThread("name2")
    t1.start()
    t2.start()
    t1.join()
    t2.join()
    print("程序執(zhí)行結束.....")

重寫run方法實現(xiàn)剛才爬蟲多線程案例

import threading
import time
from urllib.request import urlopen
def timeit(f):
    def wrapper(*args, **kwargs):
        start_time = time.time()
        res = f(*args, **kwargs)
        end_time = time.time()
        print("%s函數(shù)運行時間:%.2f" % (f.__name__, end_time - start_time))
        return res
    return wrapper
class MyThread(threading.Thread):
    def __init__(self, ip):
        super(MyThread, self).__init__()
        self.ip = ip
    def run(self):
        url = "http://ip-api.com/json/%s" % (self.ip)
        urlObj = urlopen(url)
        # 服務端返回的頁面信息, 此處為字符串類型
        pageContent = urlObj.read().decode('utf-8')
        # 2. 處理Json數(shù)據(jù)
        import json
        # 解碼: 將json數(shù)據(jù)格式解碼為python可以識別的對象;
        dict_data = json.loads(pageContent)
        print("""
                            %s
        所在城市: %s
        所在國家: %s
        
        """ % (self.ip, dict_data['city'], dict_data['country']))
@timeit
def main():
    ips = ['12.13.14.%s' % (i + 1) for i in range(10)]
    threads = []
    for ip in ips:
        # 實例化自己重寫的類
        t = MyThread(ip)
        threads.append(t)
        t.start()
    [thread.join() for thread in threads]
if __name__ == '__main__':
    main()

以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。如有錯誤或未考慮完全的地方,望不吝賜教。

相關文章

  • 10分鐘用Python快速搭建全文搜索引擎詳解流程

    10分鐘用Python快速搭建全文搜索引擎詳解流程

    讀萬卷書不如行萬里路,只學書上的理論是遠遠不夠的,只有在實戰(zhàn)中才能獲得能力的提升,本篇文章帶你用python花10分鐘迅速搭建一個好玩的Python全文搜索引擎,大家可以在過程中查缺補漏,提升水平
    2021-10-10
  • 使用Python找出水仙花數(shù)的方法介紹

    使用Python找出水仙花數(shù)的方法介紹

    水仙花數(shù)也被稱為超完全數(shù)字不變數(shù)、自戀數(shù)、自冪數(shù)、阿姆斯壯數(shù)或阿姆斯特朗數(shù),水仙花數(shù)是指一個3位數(shù),本文就給大家簡單聊聊如何使用Python找出水仙花數(shù),感興趣的同學可以參考閱讀
    2023-07-07
  • python使用ctypes調(diào)用dll遇到的坑解決記錄

    python使用ctypes調(diào)用dll遇到的坑解決記錄

    這篇文章主要為大家介紹了python使用ctypes調(diào)用dll遇到的坑解決記錄,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪
    2023-12-12
  • Python里隱藏的“禪”

    Python里隱藏的“禪”

    這篇文章主要介紹了IT柏拉圖翻譯的python的lib目錄下this.py文件中的一首詩,蘊含了Python程序設計中很多哲理性的規(guī)律,需要的朋友可以參考下
    2014-06-06
  • python清空命令行方式

    python清空命令行方式

    今天小編就為大家分享一篇python清空命令行方式,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2020-01-01
  • 用Python中的__slots__緩存資源以節(jié)省內(nèi)存開銷的方法

    用Python中的__slots__緩存資源以節(jié)省內(nèi)存開銷的方法

    這篇文章主要介紹了用Python中的__slots__通過緩存資源的方式以節(jié)省內(nèi)存開銷的方法,且示例代碼非常簡單,需要的朋友可以參考下
    2015-04-04
  • Python中使用gzip模塊壓縮文件的簡單教程

    Python中使用gzip模塊壓縮文件的簡單教程

    這篇文章主要介紹了Python中使用gzip模塊壓縮文件的簡單教程,本文的例子主要針對類UNIXZ系統(tǒng),需要的朋友可以參考下
    2015-04-04
  • python3中datetime庫,time庫以及pandas中的時間函數(shù)區(qū)別與詳解

    python3中datetime庫,time庫以及pandas中的時間函數(shù)區(qū)別與詳解

    這篇文章主要介紹了python3中datetime庫,time庫以及pandas中的時間函數(shù)區(qū)別與詳解,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2020-04-04
  • 解決python 虛擬環(huán)境刪除包無法加載的問題

    解決python 虛擬環(huán)境刪除包無法加載的問題

    這篇文章主要介紹了解決python 虛擬環(huán)境刪除包無法加載的問題,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2020-07-07
  • Python實現(xiàn)Logger打印功能的方法詳解

    Python實現(xiàn)Logger打印功能的方法詳解

    最近工作中遇到了打印的需求,通過查找相關的資料發(fā)現(xiàn)Python中Logger可以很好的實現(xiàn)打印,所以下面這篇文章主要給大家介紹了關于Python如何實現(xiàn)Logger打印功能的相關資料,文中通過示例代碼介紹的非常詳細,需要的朋友可以參考下。
    2017-09-09

最新評論