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()