python多線程之從Thread類繼承

本文首發於知乎php

上一篇文章實現多線程的方式是html

  • 建立函數
  • Thread函數建立進程,將要運行的函數傳入其中

本文咱們講另外一種實現多線程的方式————從threading.Thread類繼承出一個新類,主要實現__init__run方法python

首先咱們來看一個最簡單的例子,只實現了run方法編程

import time
import threading
class MyThread(threading.Thread):
def run(self):
time.sleep(1)
a = 1 + 1
print(a)
for _ in range(5):
th = MyThread()
th.start()
複製代碼

總結一下ruby

  • 定義一個類,繼承threading.Thread類,裏面只須要定義run方法
  • run方法至關於以前傳入Thread的那個函數,注意只能用run這個名字,不用顯式調用,線程start()時會自動調用run
  • 建立類的實例時不須要傳入參數,獲得的結果就能夠調用start join等方法
  • 上一篇文章提過Thread對象能夠調用start join run等方法,其實當時調用start就自動調用了run。這裏只不過是在新類中重寫了run方法,線程調用start時就會自動執行這個run

上面每次運行的run都是同樣的,真正使用時不多會這樣用,有時會須要傳入一些區別性的參數,這就須要定義類的__init__了,咱們來看下面的例子多線程

import threading
import requests
from bs4 import BeautifulSoup
class MyThread(threading.Thread):
def __init__(self, i):
threading.Thread.__init__(self)
self.i = i
def run(self):
url = 'https://movie.douban.com/top250?start={}&filter='.format(self.i*25)
r = requests.get(url)
soup = BeautifulSoup(r.content, 'html.parser')
lis = soup.find('ol', class_='grid_view').find_all('li')
for li in lis:
title = li.find('span', class_="title").text
print(title)
for i in range(10):
th = MyThread(i)
th.start()
複製代碼

上面代碼實現10個線程抓取豆瓣top250網站10頁的電影名,經過__init__將循環信息傳到類之中。app

上一篇文章不使用類來使用多線程時,講了Thread函數的參數,Thread對象的方法和一些能夠直接調用的變量,這裏咱們分別講一下函數

  • Thread函數的參數。初始化線程時傳入一些參數,這裏也能夠在__init__中定義
  • Thread對象的方法。這裏能夠用self直接調用這些方法
  • threading.activeCount()等直接調用的變量。在這裏依然能夠調用

因此用類的方法不會有任何限制,下面來看一個使用的例子網站

import time
import threading
class MyThread(threading.Thread):
def __init__(self, name):
threading.Thread.__init__(self)
self.name = name
def run(self):
a = 1 + 1
print(threading.currentThread().name)
time.sleep(1)
print(self.name)
time.sleep(1)
print(self.is_alive())
t = time.time()
ths = [MyThread('thread {}'.format(i)) for i in range(3)]
for th in ths:
th.start()
print(threading.activeCount())
for th in ths:
th.join()
print(time.time() - t)
複製代碼

返回結果以下url

thread 0
thread 1
thread 2
4
thread 0
thread 2
thread 1
True
True
True
2.0039498805999756
複製代碼

使用類繼承方式其實還有另外一種形式。

以前是直接用run定義計算函數,若是已經有一個計算函數,也能夠用傳入的方式而不是改寫成run

import threading
import requests
from bs4 import BeautifulSoup
def gettitle(page):
url = 'https://movie.douban.com/top250?start={}&filter='.format(page*25)
r = requests.get(url)
soup = BeautifulSoup(r.content, 'html.parser')
lis = soup.find('ol', class_='grid_view').find_all('li')
for li in lis:
title = li.find('span', class_="title").text
print(title)
class MyThread(threading.Thread):
def __init__(self, target, **args):
threading.Thread.__init__(self)
self.target = target
self.args = args
def run(self):
self.target(**self.args)
for i in range(10):
th = MyThread(gettitle, page = i)
th.start()
複製代碼

歡迎關注個人知乎專欄

專欄主頁:python編程

專欄目錄:目錄

版本說明:軟件及包版本說明

相關文章
相關標籤/搜索