简体   繁体   中英

How to wait until thread is finished

I'm looking for some advice on the best way to implement the task below (my current method is quite naive and is causing me issues)

Here is the run down on what should happen when my app is started:

  1. First the user is prompted to login to facebook. I use facebooks DialogListener to listen for when it completes.

  2. On completion of above task I use an AsyncFacebookRunner to collect some information about the user. I use the AsyncFacebookRunner.RequestListener() to listen for when this completes.

  3. On completion of task 2 I store some information in SharedPreferences

This all works splendidly. Here is the issue... I need to use some of said information in a http POST to get data on the server. The data is used to populate a gridview. For this I am using a Asynctask. My problem lies in not knowing when the data is there in SharedPreferences.

As of right now in the doInBackground I have a loop like this:

while (true)
{
    if (not a valid value of something in SharedPreferences)
         Thread.sleep(500);
    else
         break
}

Which is incredibly ugly, naive, and is giving me some issues. At this point I feel like I should rewrite the whole thing so hopefully somebody can suggest a better method!

使用SharedPreferences注册OnSharedPreferenceChangedListener ,以便在数据发生变化时收到通知。

If I understand your order of events correctly. When #3 is running and saving the preferences, why can't it notify anything waiting on the values it is writing to SharedPreferences? Event style. That will eliminate the spin wait you're currently using.

Perhaps I missed something?

There various ways to perform this. You can use blocking queue to do this. So when there is valid SharedPreferences ie in the queue it will be consumed by the thread.

private volatile boolean mLock = false;

void otherThreadFunc() {
    mLock = true;
    Thread.sleep(10000);
    mLock = false;
}

void mainThread() {
    new Thread(new Runnable() {
        public void run() {
            otherThreadFund();
        }
    }.start();

    // Wait...
    while(mLock) {
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM