写一个多线程读取json
时间: 2023-11-18 16:57:27 浏览: 29
下面是一个多线程读取 JSON 的示例代码:
```python
import json
import threading
# 定义一个函数用于读取 JSON 文件
def read_json(filename):
with open(filename) as f:
data = json.load(f)
print(data)
# 定义一个线程类
class ReadJsonThread(threading.Thread):
def __init__(self, filename):
threading.Thread.__init__(self)
self.filename = filename
def run(self):
read_json(self.filename)
# 创建多个线程
threads = []
for i in range(5):
thread = ReadJsonThread(f"data_{i}.json")
threads.append(thread)
# 启动多个线程
for thread in threads:
thread.start()
# 等待所有线程执行完毕
for thread in threads:
thread.join()
```
上面的代码中,我们首先定义了一个 `read_json` 函数用于读取 JSON 文件。然后定义了一个 `ReadJsonThread` 类,继承自 `threading.Thread` 类,这个类中有一个 `run` 方法,用于执行读取 JSON 文件的操作。接着,我们创建了多个 `ReadJsonThread` 类的实例,并将它们添加到一个列表中。最后,我们依次启动每个线程,并等待所有线程执行完毕。这样就可以实现多线程读取 JSON 文件了。