CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutSign UpSign In
jackfrued

CoCalc provides the best real-time collaborative environment for Jupyter Notebooks, LaTeX documents, and SageMath, scalable from individual users to large groups and classes!

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