Skip to content

Instantly share code, notes, and snippets.

@zhyq0826 zhyq0826/python_thread.py
Last active Sep 5, 2016

Embed
What would you like to do?
python 多线程
import urllib2
import time
from threading import Thread
def get_responses():
urls = ['http://www.baidu.com', 'http://www.amazon.cn', 'http://www.taobao.com', 'http://www.alibaba.com']
start = time.time()
for url in urls:
print url
resp = urllib2.urlopen(url)
print resp.getcode()
print "Elapsed time: %s" % (time.time()-start)
class GetUrlThread(Thread):
def __init__(self, url):
self.url = url
super(GetUrlThread, self).__init__()
def run(self):
resp = urllib2.urlopen(self.url)
print self.url, resp.getcode()
def get_responses_thread():
urls = ['http://www.baidu.com', 'http://www.amazon.cn', 'http://www.taobao.com', 'http://www.alibaba.com']
start = time.time()
threads = []
for url in urls:
t = GetUrlThread(url)
threads.append(t)
t.start()
for t in threads:
t.join()
print "Elapsed time: %s" % (time.time()-start)
if __name__ == '__main__':
get_responses()
get_responses_thread()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.