开发者

How to make threads synchronize in a loop statement?

I am new to threads. I am trying to load a small array of photos. Right now I am using Async tasks/ threads, but how do I make the outcome sequential? Below is an illustration:

What I want:

a[0] = phot开发者_如何学Co1;
a[1] = photo2;
a[2] = photo3;
a[3] = photo4

What my program gives me instead. Note that the order changes and is random:

a[0] = photo[2];
a[1] = photo[1];
a[2] = etc

Here's a snippet of my code:

...
for (int i = 0; i < mNoOfContacts; i++) {
    String stringContactUri = storeSettings.getString("contactUri"+i, "");
    if (stringContactUri != ""){
        Uri contactUri = Uri.parse(stringContactUri);
        loadContactInfo(contactUri);
    }
...
private void loadContactInfo(Uri contactUri) {

    AsyncTask<Uri, Void, ContactInfo> task = new AsyncTask<Uri, Void, ContactInfo>() {

        @Override
        protected ContactInfo doInBackground(Uri... uris) {             
            return mContactAccessor.loadContact(getContentResolver(), uris[0]);
        }

        @Override
        protected void onPostExecute(ContactInfo result) {
            Contacts[mNoOfContacts] = result;
        Toast.makeText(getApplicationContext(), mNoOfContacts+"Picked Contact"+Contacts[mNoOfContacts].getDisplayName(), Toast.LENGTH_SHORT).show();
            mNoOfContacts++;
        } 
    };

    task.execute(contactUri);
}
...

My code is a modification of the Google Android demo app - Business Cards. Please help! Thanks!


What might be the easiest thing to do is make the onPostExecute method call a routine that does the sorting: pass both the ContactInfo and the Uri and then compare the Uri with the original and put it in the proper place.

Alternatively modify your AsyncTask so instead of launching one per Uri you launch one you pass all the Uris at once and then go from there.


I would think that, by definition, "Asynchronous Tasks" are not synchronized...Asynchronous literally means "not synchronized." If you want it synchronized, just load them the old fashioned way by doing a URI call, get your photo and do it again once the last photo was loaded.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜