多線程threading
阿新 • • 發佈:2018-03-31
blog 循環 rt thread imp 字符 AD 轉換 import args
#-*-coding:utf-8-*-
import threading #創建多線程(thread二次封裝)
from time import ctime,sleep
import time
def listen(name):
print (‘begin listening to {name} {time}‘.format(name=‘shabi‘,time=ctime()))#類似html的變量,ctime 時間轉換成字符串
time.sleep(3)
print (‘over {time}‘.format(name=‘shabi‘,time=ctime()))
def func(name):
print (‘{name} running.{time}‘.format(name=name,time=ctime()))
time.sleep(5)
print (‘{name} running over.{time}‘.format(name=name,time=ctime()))
t1=threading.Thread(target=listen,args=(‘egon‘,)) #實例化,target執行線程名即函數,args傳的參數,要以元祖的形式
t2=threading.Thread(target=func,args=(‘alex‘,))
print (‘game over {time}‘.format(time=ctime()))#主線程必須放在分支線程的start執行前
# t1.start()
# t2.start()
t1.join()#主線程必須等待線程t1執行完
threads=[] #通過列表添加順序for循環,控制執行順序,但不能決定誰先執行完
threads.append(t2)
threads.append(t1)
for i in threads:
i.start()#執行命令內部函數
多線程threading