Last active
September 5, 2016 07:04
-
-
Save zhyq0826/c5a8c999093479b009e0876362e5c506 to your computer and use it in GitHub Desktop.
python 多线程
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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