python复习之多线程编程

1.多线程编程的定义

def myThread(arg1,arg2):
    print('%s %s' %(arg1, arg2))

for i in range(1, 6, 1):
    t1 = myThread(i, i+1)

运行结果:

1 2
2 3
3 4
4 5
5 6

这是没有多线程编程,用的是循环来做的,在运行的时候从for开始运行,然后依次调用函数

import threading
import time
from  threading import current_thread

def myThread(arg1,arg2):
    print(current_thread().getName(),'start')	#获取当前线程的标志
    print('%s %s' %(arg1, arg2))
    time.sleep(1)
    print(current_thread().getName(), 'stop')

for i in range(1, 6, 1):
    #t1 = myThread(i, i+1)
    t1 = threading.Thread(target = myThread, args=(i, i+1))
    t1.start()  #多线程方法才可以正常运行

print(current_thread().getName(),'end')

运行结果:

Thread-1 start		#如果是多线程,就会给多线程取一个名字
1 2
Thread-2 start
2 3
Thread-3 start
3 4
Thread-4 start
4 5
Thread-5 start
5 6
MainThread end
Thread-5 Thread-3stop stop
Thread-4Thread-2
Thread-1 stop
 stop
 stop

从上可知,我们的线程是可以并行运行的
线程先结束,主线程后结束

import threading
from threading import current_thread

class Mythread(threading.Thread):
    def run(self):
        print(current_thread().getName(),'start')
        print('run')
        print(current_thread().getName(),'end')

t1 = Mythread()
t1.start()
t1.join()   #线程先结束,主线程后结束
print(current_thread().getName(),'end')在这里插入代码片

2.生产者和消费者关系

from threading import Thread,current_thread
import time
import random
from queue import Queue

queue = Queue(5)    #定义队列的长度

class ProducerThread(Thread):
    def run(self):
        name = current_thread().getName() #获取当前多线程的标志
        nums = range(100)
        global queue
        while True:
            num = random.choice(nums)   #随机选择一个数字
            queue.put(num)  #向队列中添加数据
            print('生产者 %s 生产了数据 %s' %(name, num))
            t = random.randint(1,3) #经过随机的休眠时间向队列中添加数字
            time.sleep(t)
            print('生产者 %s 睡眠了 %s 秒' %(name, t))


class ConsumerThread(Thread):
    def run(self):
        name = current_thread().getName()  # 获取当前多线程的标志
        global queue
        while True:
            num = queue.get()   #从队列中取数字
            queue.task_done()   #该方法已经封装好了线程等待方法
            print('消费者 %s 消耗了数据 %s' % (name, num))
            t = random.randint(1, 3)  # 经过随机的休眠时间向队列中拿取是数字
            time.sleep(t)
            print('消费者 %s 睡眠了 %s 秒' % (name, t))

p1 = ProducerThread(name = 'p1')
p1.start()
c1 = ConsumerThread(name = 'c1')
c1.start()
c2 = ConsumerThread(name = 'c2')
c2.start()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

咸宁七s

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值