Python0225-18(多线程)

多线程
cpu:通过操作系统操作软件
程序:代码指令集合
进程:程序的执行过程
线程:指令执行的最小单元,多任务同时并发执行

线程安全:指数据安全 慢 同步
非线程安全(线程不安全):多个线程操作同一个对象 快 异步
锁?
继承方式实现多线程:
函数式实现多线程:

线程的状态(生命周期):5个状态
创建状态:----->就绪状态----->运行状态----->死亡状态
/ /
/-挂起状态-/

线程锁-互斥锁 (Lock)

#仓库存取

import threading,time
list = []
def cun(name):
    while True:
        list.append("方便面")
        print(name, "存了一袋方便面,仓库余:", len(list))
def qu(name):
    while True:
        if len(list)==0:
            time.sleep(1)
        else:
            list.pop()
            print(name,"取了一袋方便面,仓库余:",len(list))
            #time.sleep(1.5)

p1=threading.Thread(target=cun,args=("p1",))#,args=不写为空列表,不传
p2=threading.Thread(target=cun,args=("p2",))
p3=threading.Thread(target=cun,args=("p3",))
p4=threading.Thread(target=qu,args=("p4",))
p5=threading.Thread(target=qu,args=("p5",))
p6=threading.Thread(target=qu,args=("p6",))
p7=threading.Thread(target=qu,args=("p7",))

p1.start()
p2.start()
p3.start()
p4.start()
p5.start()
p6.start()
p7.start()

#继承类

import threading
class MyThread(threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self)
    def run(self):
        for i in range(100):
            print(i)

t1=MyThread()
t2=MyThread()

t1.start()
t2.start()

#锁

import  threading,time
lock=threading.Lock()
list =["烤冷面"]
def get():
    #获取锁
    lock.acquire()
    if len(list)>0:
        time.sleep(1)
        list.pop()
        print("取走一份")

#释放锁

lock.release()
t1=threading.Thread(target=get())
t2=threading.Thread(target=get())
t3=threading.Thread(target=get())

t1.start()
t2.start()
t3.start()

#仓储模型(生产消费者模型)进货取货

import threading,time
lockq=threading.Lock()
lockc=threading.Lock()
list = []
class MyThread(threading.Thread):
    def __init__(self, name):
        threading.Thread.__init__(self)
        self._name = name

    def run(self):
        while True:
            if self._name =="取货人":
                 self.qu()
                 time.sleep(1)
            else:
                while True:
                    self.cun()

    def cun(self):
        lockc.acquire()
        list.append("货")
        print("存货,剩余:",len(list))
        lockc.release()
    def qu(self):
        lockq.acquire()
        if len(list)>0:
            list.pop()
            print("取货,剩余:",len(list))
        lockq.release()

t1 = MyThread("存货人")
t2 = MyThread("存货人")
t3 = MyThread("取货人")
t4 = MyThread("取货人")
t5 = MyThread("取货人")


t1.start()
t2.start()
t3.start()
t4.start()
t5.start()
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值