I created an asynctask and in its doInBackground() method i started a thread like this:
private class myAsyntask extends Asynctask{
doInBackground(){
Thread t = new Thread(new Runnable(){
public void run()
{
while(someBoolean!=true){
Thread.currentThread.sleep(100);
}
}
});
}
onPostExecute(){
//do something related to that variable
}
}
problem I am facing is after 1st iteration of Thread.sleep()
, onPostExecute()
is called , instead I thought that asynctask will run this thread on background and when that boolean is true onPostexecute() is called.I am not able to understand why this happens ?
AsyncTask automatically creates a new Thread for you, so everything you do in doInBackground()
is on another thread.
What you are doing is this:
doInBackground()
. t
) is created from the AsyncTask-Thread. doInBackground()
is completed, as all it does is create the Thread t and thus jumps to onPostExecute()
. start()
on t
, meaning that it is not started).Instead you want your doInBackground()
method to look something like this:
doInBackground(){
while(someBoolean!=true){
//Perform some repeating action.
Thread.sleep(100);
}
}
First of all, in your code you don't even start thread t
, so all that happens in doInBackground
is creation of new thread and then moving on to onPostExecute()
.
Secondly, you don't even need separate thread, since doInBackground()
handles this for you, so you can just use something like
doInBackground(){
while(someBoolean!=true){
Thread.currentThread.sleep(100);
}
}
if you wish, however, to stick with separate thread, you can start thread and wait for it's completion by using .join(); like
doInBackground(){
Thread t = new Thread(new Runnable(){
public void run() {
while(someBoolean!=true){
Thread.currentThread.sleep(100);
}
}
});
t.start();
t.join();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With