zoukankan      html  css  js  c++  java
  • python_day29_通过类创建多线程_队列

    #Author:'haijing'
    #date:2018/12/20
    import threading
    import time
    #通过类创建多线程


    class MyThread(threading.Thread): #MyThread类继承threading.Thread类
    def __init__(self, num):
    threading.Thread.__init__(self)
    self.num = num

    def run(self): # run是threading.Thread中的方法

    print("running on number:%s" % self.num)

    time.sleep(3)


    if __name__ == '__main__': #这一句可以报程在本py文件中可以执行,在别的py文件中调用这个频域文件时候(即import ...不会去执行t1.start等)
    t1 = MyThread(1) #创建线程对象t1,执行这一句的时候,self.num=1这个变量存在了一块内存中
    t2 = MyThread(2) #创建线程对象t2,执行这一句的时候,self.num=1这个变量存在了另一块内存中,和上面的互不干扰
    t1.start() #执行线程t1 实际执行的是run方法
    t2.start() #执行线程t1

    队列
    #Author:'haijing'

    #date:2018/12/20
    # import queue
    #
    # d = queue.Queue() #创建一个队列 是用来放数据的,默认参数为0表示可以存储参数的大小为无穷大
    # d.put('jinxing') #将'jingxing'插入队列d中
    # d.put('xiaohu') #将xiaohu插入队列中,并防止jinxing的后面
    # d.put('123')
    # #默认是先进先出
    # print(d.get()) #jinxing
    # print(d.get()) #xiaohu
    # print(d.get()) #123
    # # print(d.get()) #一旦全部拿出来后,再去队列中拿数据,程序会阻塞住,因为程序一直在等待着另外的数据补充进来
    #
    # d1 = queue.Queue(4) #表示可以往d1中插入4个数据
    #但是一旦插入5个数据,如果d.put('haijing')程序就会阻塞住,除非有一个数据出去了
    #一旦插入5个数据,如果d.put('haijing',1)程序就会报错

    #队列可以解决多线程的问题
    #如果是列表,很多个线程都可以去拿最后一个数,导致不安全
    #进一步想,如果列表中的每个数都是一个任务的话,多个线程去拿同一个任务的话就不好了
    #所以用队列,一个线程get一下,下一个线程再去get肯定是拿到的下一个数
    import threading,queue
    from time import sleep
    from random import randint
    class Production(threading.Thread): #“生产线程”的类
    def run(self): #具体生产的方法
    while True:
    r=randint(0,100) #产生一个0-100之间的数
    q.put(r) #将随机产生的数字放入队列q中去
    print("生产出来%s号包子"%r)
    sleep(1) #必须有这一句,以阻塞住“生产线程”的执行,要不然就是“生产线程”一直在执行了,没有“吃的线程去执行了”
    class Proces(threading.Thread): #“吃的线程”的类
    def run(self):
    while True:
    re=q.get() #按照放进q中的顺序一个一个的拿出来,并赋值给re
    print("吃掉%s号包子"%re)
    if __name__=="__main__":
    q=queue.Queue(10) #产生一个数据大小为10的队列q
    threads=[Production(),Production(),Production(),Proces()]
    for t in threads: #类似于t1=Production()->“生产线程”对象 t2=Production()—>"生产线程"对象 t3=Production() t4=Proces()->“吃线程”对象
    t.start() #t1.start->"生产线程"执行 t2.start t2.start t2.start->“吃线程”执行

    #即创建了4个线程,cpu每次也都是执行一个线程,只不过当某个线程阻塞住(例如有延时),会去执行另外一个线程,这样来提高效率

    2018.12.20 haijing in HZ
    晚 马上回宿舍了


  • 相关阅读:
    jquery调用click事件的三种方式
    jstl标签设置通用web项目根路径
    大于等于0小于等于100的正数用正则表达式表示
    Codeforces Round #319 (Div. 1) C. Points on Plane 分块
    Codeforces Codeforces Round #319 (Div. 2) C. Vasya and Petya's Game 数学
    Codeforces Codeforces Round #319 (Div. 2) B. Modulo Sum 背包dp
    Codeforces Codeforces Round #319 (Div. 2) A. Multiplication Table 水题
    cdoj 383 japan 树状数组
    bzoj 1800: [Ahoi2009]fly 飞行棋 暴力
    BZOJ 1452: [JSOI2009]Count 二维树状数组
  • 原文地址:https://www.cnblogs.com/YiYA-blog/p/10152944.html
Copyright © 2011-2022 走看看