python中多线程

多线程基本概念:

线程: 进程中的每个子任务,不能独立存在,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('正在运行的线程',new_th)
print('正在运行的线程的个数',threading.active_count())
如图:

启动线程有两种方法:
run():方法:只能执行主线程  即:只能执行一个线程
start()方法:多个线程 并行执行

实现线程的两种方式

一:类方式

import threading,time
class Mythread(threading.Thread):
     def __init__(self):
         threading.Thread.__init__(self)
         print("Mythread __init__")
     def run(self):
        for i in range(10):
            print(self.getName(),i)
            time.sleep(0.1)#停留的时间(单位为秒)
创建两个线程让他们同时执行
t1 = Mythread()
t2 = Mythread()
t1.start()
t2.start()
input()#保证主线程不死
如图:

1.

2.结果

for i in range(10):
    print(threading.current_thread().getName(),i)
    time.sleep(0.1)
    if i==5:
        #谁那个人线程调用 哪个线程停止
        #t1:强制停留0.2 秒时长 就开始恢复到就绪状态
        t1.join(0.2)
new_th=threading.enumerate()
print('正在运行的线程:',new_th)
如图:
1.

2.运行结果

二:函数实现方式:
import threading
import time
# 资源共享
nums=10
def something(x):
    for i in range(1,x):
        global nums
        nums=nums+1
        print(nums)
        time.sleep(0.2) #停留时间  /秒
threading._start_new_thread(something,(11,))
threading._start_new_thread(something,(11,))
input()
如图:

即:从11--30


案例:抢票
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))
threading._start_new_thread(something,('妞妞',))
threading._start_new_thread(something,('小红',))
threading._start_new_thread(something,('小明',))
print(threading.enumerate())
input()
如图:

更完美的:
import threading,time
nums = 50
count = 0
lock=threading.Lock() #声明一把锁
Cond=threading.Condition(lock=lock)#管理一把锁
class qiangpiao(threading.Thread):
    def __init__(self,name):
        threading.Thread.__init__(self)
        self.setName(name)
    def run(self):
        global nums,count
        while True:
            Cond.acquire()#当哪个线程获得了资源 就加上锁
            if nums == 0:
                return
            nums = nums - 1
            count = count + 1
            print('{0}抢到了{1} 剩余{2}'.format(self.getName(),count,nums))
            time.sleep(0.2)
            Cond.release()#当哪个线程完成了处理 就解开锁
if __name__ =='__main__':
    huangniu=qiangpiao('黄牛')
    shouji=qiangpiao('手机')
    chuangkou=qiangpiao('窗口')
    huangniu.start()
    shouji.start()
    chuangkou.start()
如图:
1.

2.运行结果:



知识延伸之超级案例:

 多线程:蒸馒头
import threading,time
zhenglong=[] #蒸笼
#创建2把锁 一把蒸馒头的锁 由伙夫掌管
# 另一把吃馒头的锁 由吃货 掌管

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:
                mantou=zhenglong.pop()
                print('{0} 吃了第{1}个馒头 剩余{2}个馒头'.format(self.getName(),mantou,len(zhenglong)))
                time.sleep(0.1)
            chi_Cond.release()
W=huofu('伙夫')
youran=chihuo('悠然')
niuniu=chihuo('妞妞')
xiaoming=chihuo('小明')
W.start()
youran.start()
niuniu.start()
xiaoming.start()
#保证主线程不死
input()
如图:
无限循环

完毕!

猜你喜欢

转载自blog.csdn.net/angelayouran/article/details/80543809