multithread3.py 1.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. """
  2. 使用多线程的情况 - 模拟多个下载任务
  3. Version: 0.1
  4. Author: 骆昊
  5. Date: 2018-03-20
  6. """
  7. from random import randint
  8. from time import time, sleep
  9. import threading
  10. class DownloadTask(threading.Thread):
  11. def __init__(self, filename):
  12. super().__init__()
  13. self._filename = filename
  14. def run(self):
  15. print('开始下载%s...' % self._filename)
  16. time_to_download = randint(5, 10)
  17. print('剩余时间%d秒.' % time_to_download)
  18. sleep(time_to_download)
  19. print('%s下载完成!' % self._filename)
  20. def main():
  21. start = time()
  22. # 将多个下载任务放到多个线程中执行
  23. # 通过自定义的线程类创建线程对象 线程启动后会回调执行run方法
  24. thread1 = DownloadTask('Python从入门到住院.pdf')
  25. thread1.start()
  26. thread2 = DownloadTask('Peking Hot.avi')
  27. thread2.start()
  28. thread1.join()
  29. thread2.join()
  30. end = time()
  31. print('总共耗费了%.3f秒' % (end - start))
  32. if __name__ == '__main__':
  33. main()
  34. # 请注意通过threading.Thread创建的线程默认是非守护线程