python的threading库查询现在正在运行的线程有哪些,各线程状态是
时间: 2024-04-14 16:25:29 浏览: 21
您可以使用`threading.enumerate()`方法来查询当前正在运行的线程。该方法会返回一个线程对象列表,其中包含所有当前活动的线程。
要获取每个线程的状态,您可以使用`threading.Thread`对象的`is_alive()`方法。该方法返回一个布尔值,表示线程是否仍在运行。您还可以使用`threading.Thread`对象的`name`属性来获取线程的名称。
以下是一个示例代码:
```python
import threading
def my_function():
print("Hello from thread!")
# 创建并启动线程
thread1 = threading.Thread(target=my_function, name="Thread 1")
thread1.start()
thread2 = threading.Thread(target=my_function, name="Thread 2")
thread2.start()
# 查询当前运行的线程
active_threads = threading.enumerate()
# 打印每个线程的状态和名称
for thread in active_threads:
print(f"Thread '{thread.name}' is {'running' if thread.is_alive() else 'not running'}")
```
输出结果类似于:
```
Thread 'MainThread' is running
Thread 'Thread 1' is running
Thread 'Thread 2' is running
```
请注意,主线程(即您的程序入口点)在默认情况下称为`MainThread`。