Python线程

进程:应用程序的执行实例,有独立的内存空间和系统资源

线程:CPU调度和分派的基本单位,进程中执行运算的最小单位,可完成一个独立的顺序控制流程

多线程:在一个进程中同时运行了多个线程,完成不同的工作,称之为'多线程',其交替占用CPU资源,并非真正的并行执行

多线程好处:①充分利用CPU资源②简化编程模型③带来良好的用户体验

import threading
print([x for x in range(9)])
thread=threading.current_thread()
thread.setName('主线程')
print('thread name:',thread.getName())
new_th=threading.enumerate()
print('正在运行的线程:',len(new_th))
print('正在运行的线程个数:',threading.active_count())

线程类:
1.继承threading.Thread 
2.写构造方法,且必须调用父类的构造方法
3.重写父类的run方法,会在start之后自动调用
4.实现开始方法,如果重写了start()方法,一定要调用父类的start()

import threading,time
class Mythread(threading.Thread):
    def __init__(self):
        super().__init__(self)
        print('Mythread __init__()')
    def run(self):
        for i in range(10):
            print(self.getName(),i)
            time.sleep(0.5)
t1=Mythread()
t2=Mythread()
t1.start()
t2.start()
for i in range(10):
    print(threading.current_thread().getName(), i)
    time.sleep(0.5)
    if i ==5:
        t1.join(0.2)#哪个线程调用 哪个线程停止   0.2等待时长恢复到初始状态
new_th=threading.enumerate()
print('正在运行的线程:',new_th)

函数实现方式:线程必须依赖函数实现,不能单独运行。当函数结束,线程结束。所以如果想让线程一直运行,就要想办法让程序不结束,比如在程序最后加一个input(),或死循环。

import  threading,time
nums=50
count=0
#资源共享
def something(x):
    global nums ,count
    while True:
        if nums==0:
            return
        nums=nums-1
        count=count+1
        print('{0}抢到了{1}剩余{2}'.format(x,count,nums))
    # for i in range(1,x):
    #     global nums
    #     nums=nums-1
    #     print(nums)
    #     time.sleep(0.2)
threading._start_new_thread(something,('郝瑞',))
threading._start_new_thread(something,('doudou',))
threading._start_new_thread(something,('doudou2',))
input()

蒸包子小实例子:

import threading,time
zhenglong=[]#共享数据的蒸笼
#创建两把锁 一把蒸馒头的锁 由伙夫掌管
#另外一把吃馒头的锁 由吃货掌管
zheng_lock=threading.Lock()
zheng_Cond=threading.Condition(lock=zheng_lock)
chi_lock=threading.Lock()
chi_Cond=threading.Condition(lock=chi_lock)
class huofu(threading.Thread):
    def __init__(self,name):
        threading.Thread.__init__(self)
        self.setName(name)
    def run(self):
        while True:
            chi_Cond.acquire()#被谁唤醒
            if len(zhenglong)==0:
                #开始蒸包子
                for i in range(1,11):
                    zhenglong.append(i)
                    time.sleep(0.1)
                    print('正在蒸第{0}个包子'.format(i))
                print('包子蒸完了 唤醒吃货们开始吃包子...')
                chi_Cond.notify_all()#唤醒了吃货们
            chi_Cond.release()#唤醒了伙夫 他就释放
            #伙夫进入休眠
            zheng_Cond.acquire()
            zheng_Cond.wait()
            zheng_Cond.release()
class chihuo(threading.Thread):
    def __init__(self,name):
        threading.Thread.__init__(self)
        self.setName(name)
    def run(self):
        while True:
            chi_Cond.acquire()#同一时刻只有一个吃货在获取 吃包子的资源
            global zhenglong
            if len(zhenglong)==0:
                #开始呼唤伙夫 只叫一次 蒸包子 我和其他吃货一起进入休眠
                zheng_Cond.acquire()#锁定叫醒伙夫的线程
                zheng_Cond.notify()#唤醒
                zheng_Cond.release()#释放
                chi_Cond.wait()#这个吃货进入休眠
            else:
                baozi=zhenglong.pop()
                print('{0}吃了第{1}个包子 剩余{2}个包子'.format(self.getName(),baozi,len(zhenglong)))
                time.sleep(0.1)
            chi_Cond.release()
W=huofu('伙夫')
xiaogang=chihuo('小刚')
xiaoming=chihuo('小明')
xiaopangzi=chihuo('小胖子')
W.start()
xiaogang.start()
xiaoming.start()
xiaopangzi.start()
#主线程不死
input()




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值