threading线程例子 (27-08)

利用阻塞的时间空闲去执行另一个子线程

import threading
from time import ctime, sleep

def music(func):  
  for i in range(2):
    print(func, ctime())      # 1 执行  # 4 执行  
    sleep(1)       # 阻塞
    print("end music", ctime())  # 3 执行  # 5 执行

def move(func):
  for i in range(2):
    print(func, ctime())      # 2 执行  # 7 执行
    sleep(5)       # 阻塞
    print("end move", ctime())  # 6 执行  # 8 执行

threads=[]
t1 = threading.Thread(target=music,args=("小苹果",))
threads.append(t1)
t2 = threading.Thread(target=move,args=("华尔街之狼",))
threads.append(t2)


if __name__ == "__main__":   
  for t in threads:    # 遍历执行两个子线程
    t.start()      
# 整体执行时间为10秒

代码运行结果:

小苹果 Fri Sep  7 16:19:09 2018
华尔街之狼 Fri Sep  7 16:19:09 2018
end music Fri Sep  7 16:19:10 2018
小苹果 Fri Sep  7 16:19:10 2018
end music Fri Sep  7 16:19:11 2018
end move Fri Sep  7 16:19:14 2018
华尔街之狼 Fri Sep  7 16:19:14 2018
end move Fri Sep  7 16:19:19 2018    

 

posted @ 2018-09-07 16:36  Kay_xs  阅读(70)  评论(0编辑  收藏  举报