创建公共线程类,提供获取线程的方法
时间: 2023-11-30 22:05:04 浏览: 10
好的,以下是一个示例的公共线程类:
```python
import threading
class PublicThread(threading.Thread):
"""
公共线程类
"""
def __init__(self, target, args=()):
super(PublicThread, self).__init__()
self.target = target
self.args = args
def run(self):
self.target(*self.args)
@staticmethod
def get_threads():
"""
获取当前正在运行的所有线程
"""
return threading.enumerate()
```
使用方法:
```python
def my_func(name):
print(f"Hello, {name}!")
# 创建线程实例
thread = PublicThread(target=my_func, args=("Alice",))
# 启动线程
thread.start()
# 获取所有正在运行的线程
threads = PublicThread.get_threads()
print(threads)
```
输出:
```
[<_MainThread(MainThread, started 12345)>, <PublicThread(PublicThread, started 67890)>]
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)