Bin.L

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::
  13 随笔 :: 0 文章 :: 0 评论 :: 0 引用
#-*-coding:utf-8-*-
'''python标准库提供了两个多线程模块,分别为thread和threading,
其中thread模块是低级模块,threading是高级模块,对thread进行了封装,
绝大多数情况下,只需要使用threading这个高级模块'''
#使用threading模块创建多线程
#方式一:把一个函数传入并穿件Thread实例,然后调用start方法开始执行
import random
import time,threading

#新线程执行的代码
# def thread_run(urls):
#     print("Current %s is running...."% threading.current_thread().name)
#     for url in urls:
#         print('%s--->>>%s'%(threading.current_thread().name,url))
#         time.sleep(random.random())
#     print("%s ended." % threading.current_thread().name)
# print("%s is runing..."%threading.current_thread().name)
# t1=threading.Thread(target=thread_run,name='Thread_1',args=(['url_1','url_2','url_3']))
# t2=threading.Thread(target=thread_run,name='Thread_1',args=(['url_4','url_5','url_6']))
# t1.start()
# t2.start()
# t1.join()
# t2.join()
# print("%s ended."% threading.current_thread().name)
#方式二:直接从threading.Thread集成并穿件线程类,然后重新__init__方法和run方法
class myThread(threading.Thread):
    def __init__(self,name,urls):
        threading.Thread.__init__(self,name=name)
        self.urls=urls
    def run(self):
        print("Current %s is running..."%threading.current_thread().name)
        for url in self.urls:
            print("%s--->>>%s"%(threading.current_thread().name,url))
            time.sleep(random.random())
print("%s is running..."%threading.current_thread().name)
t1=myThread(name='Thread 1',urls=['url_1','url_2','url_3'])
t2=myThread(name='Thread 2',urls=['url_4','url_5','url_6'])
t1.start()
t2.start()
t1.join()
t2.join()
print("%s ended "% threading.current_thread().name)
        

 摘自《Python爬虫开发与项目实战》

posted on 2018-03-12 08:58  Bin.L  阅读(...)  评论(...编辑  收藏