• python 用Threading创建多线程


    #-*-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爬虫开发与项目实战》

  • 相关阅读:
    2003开机自动登陆然后马上锁定计算机
    修改DNS、网关的VBS代码,不需重起即时生效
    页面自动刷新代码
    dos命令给权限
    无法运行VBS代码
    去掉2003或2kserver版的系统启动报错
    让易语言的信息框总在最前
    教你轻松搞定RJ45网线接头
    小技巧:如何设定永久通用WinRAR压缩密码
    Bootstrap入门教程
  • 原文地址:https://www.cnblogs.com/bin-l/p/8547443.html
Copyright © 2020-2023  润新知