线程与线程池

2019年5月1日17:58:00 发表评论 991 views
import time
from threading import Thread
def func():
print('start')
time.sleep(2) #延时 模拟百度发出请求
print('end')
if __name__=='__main__':
# t = Thread(target=func) #创建出来的子线程
# t.start()
# print('主线程结束')
t_list=[]
for i in range(100):
t = Thread(target=func)
t_list.append(t)
# t.start()
#t.join()写到start后面就变成了一个一个执行了(join的作用是等待调用join的子现场结束)
for t in t_list:
t.start()
for ti in t_list:
t.join()
print('主线程结束')
------------------------------------------------------------------------------------
from threading import Thread
import time
class my_thread(Thread):
def __init__(self):
super(my_thread, self).__init__()
def run(self):# 必须要写 这是线程要执行的内容
print('11111')
time.sleep(2)
print('2222')
if __name__ =='__main__':
for i in range(10):
t = my_thread()
t.setDaemon(True)#设置守护线程,主线程结束时该子线程也会结束
t.start() #调用线程
print('主线程结束')
----------------------------------------------------------------------------------
from threading import Thread,Lock
x = 0
n = 100000
lock = Lock()
def incr(n):
global x
for i in range(n):
lock.acquire()
x +=1
lock.release()
def dncr(n):
global x
for i in range(n):
lock.acquire()
x -=1
lock.release()
t1 = Thread(target=incr,args=(n,))
t2 = Thread(target=dncr,args=(n,))
t1.start()
t2.start()
t1.join()#不加这两个join任然无法打印出0,因为线程未结束就print(x)了
t2.join()
print(x)
------------------------------------------------------------------------
队列
import queue
from threading import Thread
import random
q = queue.Queue(5) #实例
def incr(q):
for i in range(20):
num = random.randint(1,20)
q.put(num)
print('添加的数据为{},当前队列的长度为{}'.format(num,q.qsize()))
def dncr(q):
for i in range(20):
num = q.get()
print('获取的数据为{},当前队列的长度为{}'.format(num,q.qsize()))
t1 = Thread(target = incr,args=(q,))
t2 = Thread(target = dncr,args=(q,))
t1.start()
t2.start()
t1.join()
t2.join()
----------------------------------------------------------------------------------------

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: