代码运行结果问题
# 线程的优化,线程池怎么实现 import threading import time def run(n): """线程要做的事情""" time.sleep(2) print(threading.current_thread().name, n) def main(): """使用传统的方法来做任务""" t1 = time.time() for n in range(10): run(n) print(time.time() - t1) def main_use_thread(): """使用线程优化任务""" # 电脑资源有限,每次最多只能跑10个线程 t1 = time.time() ls = [] for count in range(10): for i in range(10): t = threading.Thread(target=run, args=(i,)) ls.append(t) t.start() for l in ls: l.join() print(time.time() - t1) if __name__ == '__main__': # main() main_use_thread()
老师,代码是这样的,和老师的代码也是一样。但是运行的结果是乱七八糟的
Thread-10 9Thread-8 Thread-9 8Thread-3 2Thread-1 0Thread-4 Thread-7 6 Thread-2 Thread-5 4 1 Thread-67 3 5 Thread-11Thread-13 0 Thread-12 1Thread-15 4Thread-16 5 Thread-14 Thread-19 Thread-20 98 Thread-17 6 Thread-18 3 7 2 Thread-27Thread-25 4Thread-28 6Thread-29 8 Thread-30Thread-22Thread-21 0 7 9 Thread-24 3 Thread-23 12 Thread-26 5 Thread-37Thread-34 Thread-40 Thread-32 1 Thread-35 43 Thread-36Thread-38 Thread-39 8 7 Thread-33 2 Thread-31 0 69 5 Thread-41 0 Thread-45Thread-50 9 Thread-43 2Thread-48 Thread-46 5 7 Thread-44 3 Thread-49 8 4 Thread-47 6 Thread-42 1 Thread-54Thread-53 Thread-57 6Thread-59 8Thread-52Thread-56 5 Thread-60 Thread-51 0 9 1 2 Thread-55Thread-58 47 3 Thread-63Thread-70Thread-65 4Thread-61 0Thread-68 Thread-62 9Thread-69 8 2 Thread-64 Thread-66 7Thread-673 51 6 Thread-75Thread-79 8 Thread-71 Thread-77 Thread-78 7 Thread-74 0Thread-76 5 Thread-80 9 4 Thread-72 163Thread-73 2 Thread-81Thread-86Thread-84 Thread-88 7 Thread-85Thread-89 03 Thread-87 Thread-90 4 6 Thread-82 8 9 Thread-83 2 15 Thread-100Thread-94 3 Thread-91 Thread-98 7Thread-92 Thread-95 4 Thread-97Thread-96 0 5Thread-93 2 Thread-99 1 6 9 8 20.140185594558716
11
收起
正在回答
1回答
同学你好:
这个输出的现象确实是正常的现象,同学可以放心学习。
线程是并发的,这样的输出结果正好能说明线程是并发(同时进行)的呀。
如果我解决了同学的问题,请采纳!学习愉快^_^。
1.Python零基础入门
- 参与学习 人
- 提交作业 2727 份
- 解答问题 8160 个
想要进入Python Web、爬虫、人工智能等高薪领域,你需要掌握本阶段的Python基础知识,课程安排带你高效学习轻松入门,学完你也能听得懂Python工程师的行业梗。
了解课程
恭喜解决一个难题,获得1积分~
来为老师/同学的回答评分吧
0 星