import threading,time
def run():
for i in range(100):
time.sleep(0.1)
print("子线程结束")
t1 = threading.Thread(target=run)
t1.setDaemon(True)#False
t1.start()
t1.join(timeout=5)
print("主线程结束")
'''
'''
import threading,time
rlock1 = threading.RLock()
rlock2 = threading.RLock()
rlock3 = threading.RLock()
rlock4 = threading.RLock()
rlock5 = threading.RLock()
class ZheXueJia():
def __init__(self,left,right):
self.left = left
self.right = right
z1 = ZheXueJia(rlock5,rlock1)
z2 = ZheXueJia(rlock1,rlock2)
z3 = ZheXueJia(rlock2,rlock3)
z4 = ZheXueJia(rlock3,rlock4)
z5 = ZheXueJia(rlock4,rlock5)
def run(z,name):
f = z.left.acquire()
if f:
print(name,"获取左筷子")
ff = z.right.acquire()
if ff:
print(name, "获取右筷子")
print("哲学家开始就餐",name)
time.sleep(1)
z.right.release()
z.left.release()
t1 = threading.Thread(target=run,args=(z1,"z1"))
t2 = threading.Thread(target=run,args=(z2,"z2"))
t3 = threading.Thread(target=run,args=(z3,"z3"))
t4 = threading.Thread(target=run,args=(z4,"z4"))
t5 = threading.Thread(target=run,args=(z5,"z5"))
t1.start()
t2.start()
t3.start()
t4.start()
t5.start()
'''
'''
#信号量
import threading,time
s = threading.Semaphore(3)
def run(name):
s.acquire()
print(name,"开始执行")
time.sleep(1)
print(name,"执行结束")
s.release()
start_time = time.time()
t1 = threading.Thread(target=run,args=("t1",))
t2 = threading.Thread(target=run,args=("t2",))
t3 = threading.Thread(target=run,args=("t3",))
t4 = threading.Thread(target=run,args=("t4",))
t5 = threading.Thread(target=run,args=("t5",))
t6 = threading.Thread(target=run,args=("t6",))
t7 = threading.Thread(target=run,args=("t7",))
t8 = threading.Thread(target=run,args=("t8",))
t9 = threading.Thread(target=run,args=("t9",))
t10 = threading.Thread(target=run,args=("t10",))
t1.start()
t2.start()
t3.start()
t4.start()
t5.start()
t6.start()
t7.start()
t8.start()
t9.start()
t10.start()
t1.join()
t2.join()
t3.join()
t4.join()
t5.join()
t6.join()
t7.join()
t8.join()
t9.join()
t10.join()
end_time = time.time()
print(end_time - start_time)
'''
#定时器
import threading
def deal_task(n):
print('%s 我被执行了~' % n)
t = threading.Timer(3, deal_task, args=(10,))
t.start()
#Event
'''
import threading,time
e = threading.Event()
def hld():
print("红灯")
time.sleep(5)
e.set()
print("绿灯")
def car_run(name):
print(name,"迎面驶来")
e.wait()
print(name,"继续前进")
for i in range(10):
t = threading.Thread(target=car_run,args=(i,))
t.start()
h = threading.Thread(target=hld,)
h.start()
'''
pythonx学习2019-2-26
最新推荐文章于 2024-03-12 23:04:05 发布