• 多线程


    #coding = utf-8
    '''
    '''
    # 生产者消费者案例
    import time
    import threading
    import random
    
    # 设定共享区
    count = 0
    # 获取条件变量对象
    condition = threading.Condition()
    
    # 定义生产者线程
    class Producer(threading.Thread):
        # 构造方法
        def __init__(self,pname):
            threading.Thread.__init__(self)
            self.pname = pname
        def run(self):
            global count
            while True:
                # 锁定共享区
                if condition.acquire():
                    # 判断共享区书否已满
                    if count >= 10:
                        print("【信息】共享区已满,生产者进入阻塞状态,请消费...")
                        #生产者线程等待
                        condition.wait()
                    else:
                        #向共享区添加数据
                        count += 1
                        print("[{0}]给共享区添加了数据1,当前共享区数据为{1}".format(self.pname,count))
                        # 唤醒消费者线程
                        condition.notify()
                    # 释放锁定
                    condition.release()
                    # 休眠
                    time.sleep(random.randint(1,5))
                pass
    
    class Customer(threading.Thread):
        # 构造方法
        def __init__(self, cname):
            threading.Thread.__init__(self)
            self.cname = cname
    
        #覆盖run放法
        def run(self):
            global count
            while True:
                if condition.acquire():
                    if count < 1:
                        print("【信息】共享区已空,消费者进入阻塞状态,请生产...")
                        condition.wait()
                    else:
                        count -= 1
                        print("[{0}]消费了数据1,当前共享区数据为{1}".format(self.cname,count))
                        #唤醒生产者线程
                        condition.notify()
                    condition.release()
                    time.sleep(random.randint(1,5))
            pass
    
    if __name__ == '__main__':
        for i in range(3):
            p = Producer("生产者{0}".format(i + 1))
            p.start()
        for i in range(3):
            c = Customer("消费者{0}".format(i + 1))
            c.start()
        pass
  • 相关阅读:
    hbase2.x错误记录之 disable表卡住
    hbase2.x 错误记录之 procedure is still running
    yarn timelineserver v2 配置
    Linux 系统出现大量的CLOSE_WAIT
    hbase 2.x 异常记录之 hbase shell不能分配内存
    spark 访问 hive,不能获取到数据信息
    hive 由于distcp导致执行sql慢
    Hbase 安装部署
    MooseFS安装部署
    hbase2.x 单节点启动,master挂掉
  • 原文地址:https://www.cnblogs.com/huazhou695/p/9889865.html
Copyright © 2020-2023  润新知