本文首发于知乎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编程
专栏目录:目录
版本说明:软件及包版本说明