一.python多线程类型总结

一.多线程 def

#coding:utf-8
import threading
import time
def run(data1,data2):
    print time.strftime('%H:%M:%S',time.localtime(time.time()))
    print threading.currentThread()
    print data1,data2
thread1=threading.Thread(target=run,name='thread1',args=('11','22',))
thread2=threading.Thread(target=run,name='thread2',args=('33','44',))
thread1.start()
thread2.start()

二.多线程类

#coding:utf-8
import threading
import time
class myThread (threading.Thread):   #继承父类threading.Thread
    def __init__(self, threadID, name, counter):
        threading.Thread.__init__(self)
        self.threadID = threadID
        self.name = name
        self.counter = counter
    def run(self):
        for i in range(self.counter):
            print threading.currentThread()
            time.sleep(self.counter/2)
            print self.name+'\t'+time.ctime()
# 创建新线程
th=[]
thread1 = th.append(myThread(1, "haha", 6))
thread2 = th.append(myThread(2, "heihei", 10))
for i in th:
    i.start()
print "Exiting Main Thread"

三.线程池

#coding:utf-8
import requests
import threading
from requests.exceptions import ConnectTimeout,HTTPError
import time
import Queue
class ThreadUrl(threading.Thread):
    def __init__(self, queue,Ttype,data):
        threading.Thread.__init__(self)
        self.queue = queue
        self.type=Ttype
        self.data=data
        self.session=requests.Session()
        self.headers = {
            "User-Agent": "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:48.0) Gecko/20100101 Firefox/48.0",
        }
        self.workpath='E:\\os\\baisi_mp4'
    def run(self):
        if self.type=='post':
            while not self.queue.empty():
                url_name = self.queue.get()
                try:
                    start_time=time.time()
                    rq=self.session.post(url=url_name,data=self.data,timeout=5)
                    end_time=time.time()
                    print end_time-start_time
                except HTTPError as e:
                    print e
                except ConnectTimeout as e:
                    print e
                self.queue.task_done()
def main(Turl,Ttype,data):
    queue=Queue.Queue()
    p=[Turl]*16
    for i in p:
        queue.put(i)
    for t in range(4):
        t=ThreadUrl(queue,Ttype,data)
        t.setDaemon(True)
        t.start()
    queue.join()
if __name__=='__main__':
    start = time.time()
    url='https://minisearch.dftoutiao.com/hotwords/hot'
    main(url,'post',{"type":'now'})

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值