python新开一个线程
时间: 2023-08-04 11:38:46 浏览: 54
在 Python 中,我们可以使用 `threading` 模块来创建新的线程。具体步骤如下:
1. 导入 `threading` 模块:
```python
import threading
```
2. 定义一个新的线程函数,例如:
```python
def thread_function():
print("This is a new thread.")
```
3. 创建新的线程对象:
```python
new_thread = threading.Thread(target=thread_function)
```
其中,`target` 参数指定了新线程所要执行的函数。
4. 启动新线程:
```python
new_thread.start()
```
5. 等待新线程执行完毕:
```python
new_thread.join()
```
这里的 `join` 方法会阻塞当前线程,直到新线程执行完毕。
完整代码示例:
```python
import threading
def thread_function():
print("This is a new thread.")
new_thread = threading.Thread(target=thread_function)
new_thread.start()
new_thread.join()
print("Main thread exiting.")
```
输出结果:
```
This is a new thread.
Main thread exiting.
```
注意,Python 中的线程是受 GIL(全局解释器锁) 控制的,因此在 CPU 密集型任务中,多线程并不会显著提高性能。如果需要进行并发处理,可以考虑使用多进程或异步编程。