本文首發於知乎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編程
專欄目錄:目錄
版本說明:軟件及包版本說明