多线程编程的定义
mport threading
def myThread(arg1, arg2):
print ("%s %s" %(arg1, arg2))
for i in range(1,6,1):
# t1 = myThread(i, i+1) # for循环
t1 = threading.Thread(target=myThread, args=(i, i + 1)) # 多线程
t1.start()
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')
thread = myThread()
thread.start()
thread.join()
print (threading.current_thread().getName(), "stop")
生产者和消费者问题
- 队列:queue
- queue.task_done().封装了join等待,可直接使用
- 如果队列满了话,生产者不再继续生产,直到消费者消费完才继续生产
- 实际工作中,在做消息服务器时不能一直储存,所以会产生消息队列
>>> import queue
>>> q = queue.Queue()
>>> q.put(1)
>>> q.put(2)
>>> q.put(3)
>>>
>>> q.get()
1
>>> q.get()
2
>>> q.get()
3
>>> q.get()
#-*-coding:utf-8-*-
from threading import Thread,current_thread
import time
import random
from queue import Queue
# 消息队列
queue = Queue(5)
class ProduceThread(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, 5)
time.sleep(t)
print ('消费者 %s 睡眠了 %s 秒' %(name. t))
p1 = ProduceThread(name = 'P1')
p1.start()
p2 = ProduceThread(name = 'P2')
p2.start()
p3 = ProduceThread(name = 'P3')
p3.start()
c1 = ConsumerThread(name = 'C1')
c1.start()
c2 = ConsumerThread(name = 'C2')
c2.start()