class Produce(threading.Thread):
def __init__(self):
super().__init__()
self.stat = "running"
def run(self):
print(self.stat)
print("over run")
pro = Produce()
pro.start()
pro.join()
-------------------------------------------------------------
import threading
import time
def worker(number):
print “worker”
time.sleep(number)
def multi_thread():
for i in xrange(5):
t = threading.Thread(target=worker,args=(i,))
t.start()
t.join()
生产者与消费者
import threading, random
from queue import Queue
data_count = random.randint(1, 100)
task_que = Queue(data_count)
def Produce():
print("Produce running")
global task_que
for i in range(data_count):
print("生产数据资料中...")
task_id = random.randint(1, 100)
task_que.put(task_id)
print("生成数据:", task_id)
print("------------------ 生成数据量:%d --------------------"%(data_count))
def Spend():
print("Spend running")
over_task = 0
global task_que
while over_task != data_count:
print("消耗数据资料中...")
task_id = task_que.get()
over_task += 1
print("消耗数据:", task_id)
print("------------------ 消耗数据量:%d --------------------"%(over_task))
produ_thr = threading.Thread(target=Produce)
spend_thr = threading.Thread(target=Spend)
spend_thr.start()
produ_thr.start()
spend_thr.join()
produ_thr.join()
print("over")