用java写一个多线程读取json
时间: 2024-05-01 11:23:02 浏览: 152
java多线程读取文件
下面是一个用Java多线程读取JSON文件的示例代码:
```java
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import org.json.JSONArray;
import org.json.JSONObject;
public class MultiThreadedJSONReader {
public static void main(String[] args) {
String filePath = "example.json";
int numThreads = 4;
ExecutorService executor = Executors.newFixedThreadPool(numThreads);
try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) {
String line;
JSONArray jsonArray = new JSONArray();
while ((line = reader.readLine()) != null) {
jsonArray.put(new JSONObject(line));
}
int chunkSize = (int) Math.ceil(jsonArray.length() / (double) numThreads);
for (int i = 0; i < numThreads; i++) {
int start = i * chunkSize;
int end = Math.min(start + chunkSize, jsonArray.length());
JSONArray chunk = new JSONArray(jsonArray.toString(start, end));
executor.execute(new JSONReaderRunnable(chunk));
}
} catch (IOException e) {
System.err.println("Error reading file: " + e.getMessage());
}
executor.shutdown();
}
private static class JSONReaderRunnable implements Runnable {
private final JSONArray jsonArray;
public JSONReaderRunnable(JSONArray jsonArray) {
this.jsonArray = jsonArray;
}
@Override
public void run() {
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
// Do something with the JSON object
}
}
}
}
```
这个示例代码将一个JSON文件分成多个块,然后为每个块创建一个线程来处理。在这个示例中,使用了Java的`ExecutorService`和`Runnable`接口来实现多线程处理。每个JSON块由一个`JSONReaderRunnable`对象处理。你可以在`JSONReaderRunnable`类的`run()`方法中编写代码来处理JSON对象。
阅读全文