写一个python多线程
时间: 2023-12-04 09:52:25 浏览: 27
示例:
```python
import threading
def print_numbers(start, end):
for i in range(start, end):
print(i)
# 创建两个线程,分别打印 0~4 和 5~9
t1 = threading.Thread(target=print_numbers, args=(0, 5))
t2 = threading.Thread(target=print_numbers, args=(5, 10))
# 启动线程
t1.start()
t2.start()
# 等待线程执行完毕
t1.join()
t2.join()
print("Done!")
```
输出结果:
```
0
1
2
3
4
5
6
7
8
9
Done!
```
在上面的例子中,我们使用了 `threading.Thread` 类来创建线程,并指定了线程要执行的函数和参数。然后通过 `start()` 方法启动线程,最后通过 `join()` 方法等待线程执行完毕。
相关问题
写一个python多线程脚本
好的,下面是一个简单的Python多线程脚本示例,它创建了5个线程来同时执行一个函数:
```python
import threading
def worker(num):
"""线程要执行的任务"""
print(f"Thread {num} is working")
threads = []
# 创建5个线程
for i in range(5):
t = threading.Thread(target=worker, args=(i,))
threads.append(t)
# 启动所有线程
for thread in threads:
thread.start()
# 等待所有线程完成
for thread in threads:
thread.join()
print("All threads have finished")
```
运行以上代码,你会看到类似如下的输出:
```
Thread 0 is working
Thread 1 is working
Thread 2 is working
Thread 3 is working
Thread 4 is working
All threads have finished
```
该脚本创建了5个线程,并且在每个线程中打印一个消息。线程的启动和等待完成是在for循环中完成的。注意,在启动线程后,主线程不会等待线程完成,而是继续执行下一行代码,因此需要使用`thread.join()`方法等待所有线程完成。最终输出的消息证明了所有线程都已经完成了任务。
写一个python多线程示例
下面是一个简单的 Python 多线程示例,用于计算并输出斐波那契数列中前 20 个数字:
```python
import threading
def fibonacci(n):
if n <= 1:
return n
else:
return (fibonacci(n-1) + fibonacci(n-2))
class FibonacciThread(threading.Thread):
def __init__(self, n):
threading.Thread.__init__(self)
self.n = n
def run(self):
result = fibonacci(self.n)
print("Fibonacci(%d) = %d" % (self.n, result))
threads = []
for i in range(20):
thread = FibonacciThread(i)
threads.append(thread)
thread.start()
for thread in threads:
thread.join()
```
该示例中,我们首先定义了一个计算斐波那契数的函数 `fibonacci`。接下来,我们定义了一个继承自 `threading.Thread` 的子类 `FibonacciThread`,该子类在初始化时接受一个整数参数 `n`,表示要计算的斐波那契数的位置。在 `run` 方法中,我们调用 `fibonacci` 函数计算斐波那契数,并将结果输出。
在主程序中,我们创建了 20 个 `FibonacciThread` 的实例,并将它们添加到一个列表中。然后,我们依次启动这些线程,并等待它们执行完毕。最后,我们输出了每个斐波那契数的值。
在实际应用中,多线程可以用于加速计算密集型任务,如图像处理、数据分析等。但需要注意的是,在多线程编程中,需要注意线程安全问题,如共享数据的同步和互斥等。