簡體   English   中英

並發修改異常如何解決?

[英]Concurrent Modification Exception How to Fix It?

嗨,我可以使用一些幫助解決我收到的並發修改異常的問題,我認為這與List的使用和線程的使用有關,這意味着我試圖同時訪問它導致它鎖定,但我不知道如何解決,有什么幫助嗎?

編輯這只會在我連續兩次運行下面的代碼后發生,並且只能正常工作一次。

全局:列出mapOverlays; PointOverlay pointOverlay;

在onCreate中:

//Get the current overlays of the mapView and store them in the list
mapOverlays = mapView.getOverlays();
//Get the image to be used as a marker
drawable = this.getResources().getDrawable(R.drawable.guy);
//Create the drawable and bind its centre to the bottom centre
pointOverlay = new PointOverlay(drawable, this);

在getLocs中:

//Used to grab location near to the phones current location and then draw
//the location within range to the map
public void getNearLocs(View v)
{
    new Thread()//create new thread
    {
    public void run()//start thread
    {
        //Grab new location
        loc = locManager.getLastKnownLocation(locManager.getBestProvider(locCriteria, true));

        //Get the lat and long
        double lat = loc.getLatitude();
        double lon = loc.getLongitude();

        //Convert these to string to prepare for sending to server
        String sLat = Double.toString(lat);
        String sLon = Double.toString(lon);

        //Add them to a name value pair
        latLonPair.add(new BasicNameValuePair("lat", sLat));
        latLonPair.add(new BasicNameValuePair("lon", sLon));
        Log.i("getNearLocs", "Lon: " + sLon + " Lat: " + sLat);//debug

        //http post
        try
        {
            //Create a new httpClient
            HttpClient httpclient = new DefaultHttpClient();
            //Create a post URL
            HttpPost httppost = new HttpPost("http://www.nhunston.com/ProjectHeat/getLocs.php");
            //set the Entity of the post (information to be sent) as a new encoded URL of which the info is the nameValuePairs         
            httppost.setEntity(new UrlEncodedFormEntity(latLonPair));
            //Execute the post using the post created earlier and assign this to a response
            HttpResponse response = httpclient.execute(httppost);//send data

            //Get the response from the PHP (server)
            InputStream in = response.getEntity().getContent();

            //Read in the data and store it in a JSONArray
            JSONArray jPointsArray = new JSONArray(convertStreamToString(in)); 

            Log.i("From Server:", jPointsArray.toString()); //log the result 

            //Clear the mapView ready for redrawing
            mapView.postInvalidate();

            //Loop through the JSONArray
            for(int i = 0; i < jPointsArray.length(); i++)
            {
                //Get the object stored at the JSONArray position i
                JSONObject jPointsObj = jPointsArray.getJSONObject(i);

                //Extract the values out of the objects by using their names
                //Cast to int 
                //Then* 1e6 to convert to micro-degrees
                GeoPoint point = new GeoPoint((int)(jPointsObj.getDouble("lat") *1e6), 
                                              (int)(jPointsObj.getDouble("lon") *1e6)); 
                //Log for debugging
                Log.i("From Server:", String.valueOf((int) (jPointsObj.getDouble("lat") * 1e6))); //log the result
                Log.i("From Server:", String.valueOf((int) (jPointsObj.getDouble("lon") * 1e6))); //log the result

                //Create a new overlayItem at the above geoPosition (text optional)
                OverlayItem overlayitem = new OverlayItem(point, "Test", "Test");

                //Add the item to the overlay
                pointOverlay.addOverlay(overlayitem);
                //Add the overlay to the mapView
                mapOverlays.add(pointOverlay);
                //mapView.refreshDrawableState();
            }   
        }
        catch(Exception e)
        {
            Log.e("getNearLocs", e.toString());
        }
    }
}.start();//start thread
}

問題可能出在您對mapOverlays.add()的調用。 這可能是在另一個線程或代碼片段遍歷列表的同時發生的。 當一個線程在集合上進行迭代(通常使用迭代器),而另一個線程嘗試從結構上更改集合時,將引發並發修改異常。

我建議尋找可以從兩個不同的線程同時訪問mapOverlays並在列表上進行同步的地方。

問題是您正在修改覆蓋項列表,而其他一些線程正在讀取該列表。

我懷疑問題與您執行后台任務的方式有關。 您只能在UI(主線程)上修改UI。 您不應該在Thread中將疊加項添加到Map中。 請查看AsyncTask,以了解如何正確執行后台任務以及更新UI。 在Android開發人員網站上閱讀有關線程化的文章也將有所幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM