multithread2.py 778 B

12345678910111213141516171819202122232425262728293031323334
  1. """
  2. 使用多线程的情况 - 模拟多个下载任务
  3. Version: 0.1
  4. Author: 骆昊
  5. Date: 2018-03-20
  6. """
  7. from random import randint
  8. from threading import Thread
  9. from time import time, sleep
  10. def download_task(filename):
  11. print('开始下载%s...' % filename)
  12. time_to_download = randint(5, 10)
  13. sleep(time_to_download)
  14. print('%s下载完成! 耗费了%d秒' % (filename, time_to_download))
  15. def main():
  16. start = time()
  17. thread1 = Thread(target=download_task, args=('Python从入门到住院.pdf',))
  18. thread1.start()
  19. thread2 = Thread(target=download_task, args=('Peking Hot.avi',))
  20. thread2.start()
  21. thread1.join()
  22. thread2.join()
  23. end = time()
  24. print('总共耗费了%.3f秒' % (end - start))
  25. if __name__ == '__main__':
  26. main()