函数的方法
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')
类的方法
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(),'stop')
t1 = Mythread()
t1.start()
t1.join()
print(current_thread().getName()
生产者与消费者练习
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,5)
time.sleep(t)
print('消费者 %s 睡眠了 %s' %(name,t))
p1 = ProducerThread()
p1.start()
p2=ProducerThread()
p2.start()
p3=ProducerThread()
p3.start()
c1 = ConsumerThread()
c1.start()
c2 = ConsumerThread()
c2.start()