new Thread(() -> { BNRoutePlanInfos routePlaneInfo = BaiduNaviManagerFactory.getRoutePlanManager().getRoutePlanInfo();if (routePlaneInfo != null) { // 获取限行数据 limitInfo = routePlaneInfo.getLimitInfo(); //3Tab数据 mRoutePlanItems = routePlaneInfo.getRouteTabInfos(); //路线详情 mRouteDetails = routePlaneInfo.getRouteDetailLists(); } }).start(); if (limitInfo != null) { for (int i = 0; i < limitInfo.size(); i++) { String[] arr = limitInfo.get(i).split(","); Log.e(TAG, "第" + arr[0] + "条路线限行消息:" + arr[1]); } } 以上代码有什么问题?如果有 请帮我改一下
时间: 2024-01-07 13:06:01 浏览: 18
以上代码存在并发问题,新开启的线程可能还未执行完毕就会执行后面的代码,导致 limitInfo 没有被赋值就被使用了,可能会抛出空指针异常。
可以使用 CountDownLatch 来解决并发问题,将获取 limitInfo 的代码放在 CountDownLatch.await() 之后,新开启的线程执行完毕后调用 CountDownLatch.countDown(),使得 await() 方法返回,然后再执行 limitInfo 的相关操作。
示例代码如下:
```
final CountDownLatch latch = new CountDownLatch(1);
BNRoutePlanInfos routePlaneInfo = BaiduNaviManagerFactory.getRoutePlanManager().getRoutePlanInfo();
if (routePlaneInfo != null) {
new Thread(() -> {
limitInfo = routePlaneInfo.getLimitInfo();
mRoutePlanItems = routePlaneInfo.getRouteTabInfos();
mRouteDetails = routePlaneInfo.getRouteDetailLists();
latch.countDown();
}).start();
try {
latch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
if (limitInfo != null) {
for (int i = 0; i < limitInfo.size(); i++) {
String[] arr = limitInfo.get(i).split(",");
Log.e(TAG, "第" + arr[0] + "条路线限行消息:" + arr[1]);
}
}
```