美文网首页
二、Python Thread

二、Python Thread

作者: 薛定谔的猫_1406 | 来源:发表于2018-04-12 11:11 被阅读0次
#对于io操作来说,多线程和多进程性能差别不大
#1.通过Thread类实例化

import time
import threading

def get_detail_html(url):
    print("get detail html started")
    time.sleep(2)
    print("get detail html end")


def get_detail_url(url):
    print("get detail url started")
    time.sleep(4)
    print("get detail url end")


#2. 通过集成Thread来实现多线程


class GetDetailHtml(threading.Thread):
    def __init__(self, name):
        super().__init__(name=name)

    def run(self):
        print("get detail html started")
        time.sleep(2)
        print("get detail html end")


class GetDetailUrl(threading.Thread):
    def __init__(self, name):
        super().__init__(name=name)

    def run(self):
        print("get detail url started")
        time.sleep(4)
        print("get detail url end")

if  __name__ == "__main__":
    thread1 = GetDetailHtml("get_detail_html")
    thread2 = GetDetailUrl("get_detail_url")
    start_time = time.time()
    thread1.start()
    thread2.start()

    thread1.join()
    thread2.join()

    #当主线程退出的时候, 子线程kill掉
    print ("last time: {}".format(time.time()-start_time))

相关文章

  • 二、Python Thread

  • python 补充学习 线程&装饰器

    python补充学习 thread _thread 调用 _thread 模块中的start_new_thread...

  • Python多线程编程(一)

    1. threading模块 Python 实现多线程编程可以通过thread模块(thread模块在Python...

  • Python-线程、线程池

    1. Python多线程 python3中常用的线程模块为:_thread(Python2中的thread)、th...

  • Python爬虫(四)--多线程

    Python-Socket网络编程 1. thread模块 python是支持多线程的, 主要是通过thread和...

  • 02-多任务

    线程 python的thread模块是比较底层的模块,python的threading模块是对thread做了一些...

  • 线程

    python的thread模块是比较底层的模块,python的threading模块是对thread做了一些包装,...

  • Python内置库:threading详解

    Python的线程操作在旧版本中使用的是thread模块,在Python2.7和Python3中引入了thread...

  • 线程

    python的thread模块是比较底层的模块,python的threading模块是对thread做了一些包装的...

  • python多任务-线程

    python的thread模块是比较底层的模块,python的threading模块是对thread做了一些包装的...

网友评论

      本文标题:二、Python Thread

      本文链接:https://www.haomeiwen.com/subject/pbrxkftx.html