本文介绍了使用 Python 多线程编程计算指定范围内的数字数量。代码示例中创建了两个线程,一个线程计算 2 到 100000 之间能被 4 整除的数字数量,另一个线程计算 100000 到 200000 之间的奇数数量。\n\npython\nimport threading\n\ndef count_divisible_by_4():\n count = 0\n for num in range(2, 100001):\n if num % 4 == 0:\n count += 1\n print("2~100000之间能被4整除的个数为:", count)\n\ndef count_odd_numbers():\n count = 0\n for num in range(100001, 200001):\n if num % 2 != 0:\n count += 1\n print("100000~200000之间的奇数个数为:", count)\n\n# 创建两个线程\nthread1 = threading.Thread(target=count_divisible_by_4)\nthread2 = threading.Thread(target=count_odd_numbers)\n\n# 启动线程\nthread1.start()\nthread2.start()\n\n# 等待两个线程执行结束\nthread1.join()\nthread2.join()\n\nprint("程序执行完毕")\n\n\n这个程序会创建两个线程,一个线程用来计算2~100000之间能整除4的个数,另一个线程用来计算100000~200000之间的奇数的个数。最后,程序会输出结果。

Python 多线程编程:计算指定范围内的数字数量

原文地址: https://www.cveoy.top/t/topic/pth4 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录