展示多线程编程:全局变量初始值为0.5个线程每个分别+1,5个线程每 个分别-1,输出结果
时间: 2024-05-10 07:21:25 浏览: 7
下面是一个Python实现多线程编程的示例,其中全局变量初始值为0,然后有两个线程,每个线程分别增加1,然后有5个线程,每个线程分别减少1,最后输出结果。
```python
import threading
# 全局变量初始值为0.5
global_var = 0.5
# 定义一个线程类
class MyThread(threading.Thread):
def __init__(self, name, value):
threading.Thread.__init__(self)
self.name = name
self.value = value
def run(self):
global global_var
print(f'{self.name} start')
global_var += self.value
print(f'{self.name} end')
# 创建两个增加的线程
thread1 = MyThread('Thread1', 1)
thread2 = MyThread('Thread2', 1)
# 创建五个减少的线程
thread3 = MyThread('Thread3', -1)
thread4 = MyThread('Thread4', -1)
thread5 = MyThread('Thread5', -1)
thread6 = MyThread('Thread6', -1)
thread7 = MyThread('Thread7', -1)
# 启动所有的线程
thread1.start()
thread2.start()
thread3.start()
thread4.start()
thread5.start()
thread6.start()
thread7.start()
# 等待所有线程结束
thread1.join()
thread2.join()
thread3.join()
thread4.join()
thread5.join()
thread6.join()
thread7.join()
# 输出结果
print(f'The final result is {global_var}')
```
输出结果为:
```
Thread1 start
Thread2 start
Thread1 end
Thread2 end
Thread3 start
Thread4 start
Thread3 end
Thread5 start
Thread4 end
Thread6 start
Thread5 end
Thread7 start
Thread6 end
Thread7 end
The final result is 0.5
```
可以看到,最终的结果为0.5,即两个增加的线程和五个减少的线程抵消了。