如何使用处理程序线程进行多线程

时间:2018-09-24 10:31:08

标签: android multithreading android-handler

我正在尝试在Google地图上移动多个标记,每个标记都在单独的线程中。目前,我在循环内使用java线程类为每个车辆创建单独的线程。这是示例代码:

private void proceedToMoveVehicle(ArrayList<RealTimeDetailsResponce> sourceList, ArrayList<RealTimeDetailsResponce> destinationList) {
    for (int i = 0; i < destinationList.size(); i++) {
        for (int j = 0; j < sourceList.size(); j++) {
            if (destinationList.get(i).getVehicleNo().equalsIgnoreCase(sourceList.get(j).getVehicleNo())) {
                final com.google.maps.model.LatLng vehicleStartPositions = new com.google.maps.model.LatLng(sourceList.get(j).getLatitude(), sourceList.get(j).getLongitude());
                final double destainationLatitude = destinationList.get(i).getLatitude();
                final double destainationLongitude = destinationList.get(i).getLongitude();
                final String vehicleTitle = sourceList.get(j).getVehicleNo();
                final com.google.maps.model.LatLng vehicleEndPositions = new com.google.maps.model.LatLng(destainationLatitude, destainationLongitude);
                final double speedValue = 0.0000;
                if (vehicleStartPositions.lat != vehicleEndPositions.lat || vehicleStartPositions.lng != vehicleEndPositions.lng) {
                    Thread thread = new Thread(new Runnable() {
                        @Override
                        public void run() {
                            getPathyFromDirectionAPiRequestNew(vehicleStartPositions, vehicleEndPositions, vehicleTitle);
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    moveVehicle(vehicleTitle, speedValue);
                                }
                            });
                        }
                    });
                    thread.start();
                }
            }
        }
    }
}

每隔5秒钟我会从服务器获取车辆的更新位置。这里的缺点是,一旦获得更新的位置,我将无法再次使用这些线程,而必须再次创建一个新线程。

我听说过android处理程序线程,因为我们可以使用Looper重用线程。有人可以通过处理程序线程帮助我做到这一点。

2 个答案:

答案 0 :(得分:0)

尝试一下:

ExecutorService executorService = Executors.newFixedThreadPool(32); // you can number of threads you want

executorService.execute(new Runnable() {
public void run() {
         //do your work1 here
    } 
});

executorService.execute(new Runnable() {
public void run() {
         //do your work2 here and so on..
    } 
});

或者您可以放一个循环。

答案 1 :(得分:0)

由于IntentServiceHandlerThread上运行,因此我认为这将回答问题。

但是HandlerThread的问题在于它在您活动的生命周期(也是IntentService)的生命周期之外运行,因此需要对其进行适当的清理,否则将导致线程泄漏。

相关问题