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 浏览: 23
以上代码存在线程安全问题,因为子线程可能还没有执行完毕,主线程就已经进入 if 判断,导致 limitInfo 为 null,从而抛出 NullPointerException 异常。可以使用 CountDownLatch 或者 Handler 来解决线程安全问题,例如:
```
CountDownLatch latch = new CountDownLatch(1);
new Thread(() -> {
BNRoutePlanInfos routePlaneInfo = BaiduNaviManagerFactory.getRoutePlanManager().getRoutePlanInfo();
if (routePlaneInfo != null) {
// 获取限行数据
limitInfo = routePlaneInfo.getLimitInfo();
//3Tab数据
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]);
}
}
```
或者:
```
Handler handler = new Handler(Looper.getMainLooper()) {
@Override
public void handleMessage(@NonNull Message msg) {
if (msg.what == 1) {
if (limitInfo != null) {
for (int i = 0; i < limitInfo.size(); i++) {
String[] arr = limitInfo.get(i).split(",");
Log.e(TAG, "第" + arr[0] + "条路线限行消息:" + arr[1]);
}
}
}
}
};
new Thread(() -> {
BNRoutePlanInfos routePlaneInfo = BaiduNaviManagerFactory.getRoutePlanManager().getRoutePlanInfo();
if (routePlaneInfo != null) {
// 获取限行数据
limitInfo = routePlaneInfo.getLimitInfo();
//3Tab数据
mRoutePlanItems = routePlaneInfo.getRouteTabInfos();
//路线详情
mRouteDetails = routePlaneInfo.getRouteDetailLists();
}
handler.sendEmptyMessage(1);
}).start();
```