简体   繁体   中英

Thread only working on second run

I have a Singleton in an Android App (which works just fine) in one of the functions I need to set data in a class variable in another thread but the data only sets if I run the function twice.

onCreate:

Thread thread;
Runnable runnables;
String recvData;

@Override
public void onCreate() {
    super.onCreate();  
    singleInstance = this;
    recvData = "one";
    Log.v("oncreate", "singleton");
}

threaded_data_set:

public String threaded_set_data() {
    runnables = new Runnable(){
        @Override
        public void run() {
            recvData = "two";
            return;
        }
    };
    thread = new Thread(runnables);
    thread.start()
    Log.v("Data", recvData);
    return recvData;
}

on the first run it logs ("Data", "one") and only on the second one it changes to ("Data", "two")

What am I doing wrong here?

The default values of recvData is:

recvData = "one";

nothing is wrong here, the

Log.v("Data", recvData);

just printed out before your thread prints out the second log message.

You are assuming the thread has finished as soon as you get to the logging statement.

Try logging the value in the thread as you set it as well, you'll see that code happens after your first logging call.

It is working right but you're expecting the thread to finish before your method moves on is all :)

Not much is going wrong here, you just aren't using the new assignment value for recvData

public String threaded_set_data()
{
    runnables = new Runnable(){

        @Override
        public void run() {
                        recvData = "two";
                        Log.v("Data", recvData);
                        //return; <-- not really needed
                    }
    };
    thread = new Thread(runnables);
    thread.start()
    Log.v("Data", recvData);
    return recvData;
}

At the first run of the thread, the latter is running in it's own thread which means that you're already returning recvData before the runnable finishes running since it's running in parallel. What you would want to do is use an AsyncTask instead.

You're seem to missing the nuances of how threads work. I think you are assuming that your threads runs and returns before your log statement, however you can't safely assume that.

Instead, try using a handler like the comment in your question. A handler is designed exactly for this type of thing. Vogella (a fantastic resource btw) does a much better job of e xplaining it so I will direct you there.

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