python 多线程并行,举个完整的代码例子
时间: 2023-07-01 10:28:14 浏览: 55
好的,下面是一个简单的多线程并行的示例代码,它会启动两个线程,分别计算从 1 到 5000000 的和和乘积,然后将结果输出到控制台上:
```python
import threading
class MyThread(threading.Thread):
def __init__(self, start, end):
threading.Thread.__init__(self)
self.start = start
self.end = end
self.result = None
def run(self):
if self.start == 1:
self.result = sum(range(self.start, self.end+1))
else:
self.result = 1
for i in range(self.start, self.end+1):
self.result *= i
thread1 = MyThread(1, 5000000)
thread2 = MyThread(1, 100)
thread1.start()
thread2.start()
thread1.join()
thread2.join()
print("Sum of 1 to 5000000:", thread1.result)
print("Product of 1 to 100:", thread2.result)
```
这段代码中,我们创建了两个线程 `thread1` 和 `thread2`,分别计算从 1 到 5000000 的和和从 1 到 100 的积。在 `MyThread` 类中,我们重写了 `run()` 方法,该方法为线程执行的方法。在 `run()` 方法中,我们根据线程的不同计算结果,并将结果存储在 `result` 属性中。然后,在主线程中启动两个线程,分别等待它们完成计算,最后输出结果。