import threading,time
print('turtle',' rabit')
def rabit():
x=0
fuck=0
while(x<100):
if(x==40 and fuck==0):
for i in range(11):
print(" ZZZZZ")
time.sleep(0.5)
fuck=1
print(" fuck!!!")
else:
if(fuck):
x+=12
else:
x+=8
time.sleep(0.5)
print(" run",x,'m')
print('rabit win!!!')
def turtle():
x=0
while(x<100):
x+=5
time.sleep(0.5)
print("run",x,'m')
print('turtle win!!!')
threads=[]
#定义线程池
t1=threading.Thread(target=rabit)
t2=threading.Thread(target=turtle)
#定义目标函数的线程
threads.append(t1)
threads.append(t2)
#将目标线程添加到要运行的多线程中
for t in threads:
t.setDaemon(True)
t.start()
'''
setDaemon(True)将线程声明为守护线程,必须在start() 方法调用之前设置,如果不设置为守护线程程序会被无限挂起。
将t1,t2都设为守护线程,即为两个线程都执行完毕时才退出,或者说等最慢的动物跑完时比赛才结束。
调用start()方法启动线程
'''
t.join()
Python的多线程可同时运行多组代码
运行结果:
turtle rabit
run 8 m
run 5 m
run 16 m
run 10 m
run 24 m
run 15 m
run 32 m
run 20 m
run 40 m
ZZZZZ
run 25 m
ZZZZZ
run 30 m
ZZZZZ
run 35 m
ZZZZZ
run 40 m
ZZZZZ
run 45 m
ZZZZZ
run 50 m
ZZZZZ
run 55 m
ZZZZZ
run 60 m
ZZZZZ
run 65 m
ZZZZZ
run 70 m
ZZZZZ
run 75 m
fuck!!!
run 80 m
run 52 m
run 85 m
run 64 m
run 90 m
run 76 m
run 95 m
run 88 m
run 100 m
turtle win!!!