Am using some method i need to some method complete to start to another method so that am using thread function, How to start one thread follow by to second thread start?
Thread thread1 = new Thread(new Runnable() {
#Override
public void run() {
try {
loadIrrigationSourceMaster();
loadIrrigationMaster();
loadSeasonMaster();
loadFactoryMaseter();
} catch (Exception e) {
e.printStackTrace();
}
}
});
thread1.start();
Thread thread2 = new Thread(new Runnable() {
#Override
public void run() {
try {
loadTransport();
plantTypeMaster();
plotOwnerTypeMaster();
ExitRatoonMaster();
} catch (Exception e) {
e.printStackTrace();
}
}
});
thread2.start();
(new Thread(new Runnable() {
#Override
public void run() {
//TODO: fist thread code here
Log.w("tag","1");
(new Thread(new Runnable() {
#Override
public void run() {
//TODO: second thread code here
Log.w("tag","2");
}
})).start();
}
})).start();
out put of above:
tag:1
tag:2
but i dont think it's a good idea . just put rest of your job in first Thread
To wait for a thread to complete its execution before moving on, you can use the join() method: docs
Specifically for your problem, you can put thread1.join(), right after the thread1.start() call. The join call will block the calling thread until thread1 is finished with its execution, so that thread2 will be initialized and executed after thread1 is finished.
Alternatively, you can also call thread1.join() in the beginning of the run() method of thread2, so that the main thread won't need to be blocked by the join() call.
Related
I have a server giving me live data in JSON format which updates every second. I have to display that in my android app.
I am a beginner and I tried Async Task updating every second via a thread and setting a delay on it.
Thread t = new Thread() {
#Override
public void run() {
try {
while (!isInterrupted()) {
Thread.sleep(1000);
runOnUiThread(new Runnable() {
#Override
public void run() {
// Perform the HTTP request for data and process the response.
counterAsyncTask task=new counterAsyncTask();
task.execute(REQUEST_URL);
}
});
}
} catch (InterruptedException e) {
}
}
};
t.start();
It runs out of memory and crashes after some time
Are there any alternates?
Try putting your code into handler thread
Runnable runnable = new Runnable() {
#Override
public void run() {
mHandler.postDelayed(this, 1000);
counterAsyncTask task=new counterAsyncTask();
task.execute(REQUEST_URL);
}
};
// start it with:
mHandler.post(runnable);
i want the AsyncTask to wait till it finishes. so i wrote the below code and i used .get() method as follows and as shown below in the code
mATDisableBT = new ATDisableBT();
but at run time the .get() doesnt force ATDisableBT to wait, becuase in the logcat i receive mixed order of messages issued from ATDisableBT and ATEnableBT
which means .get() on ATDisableBT did not force it to wait
how to force the AsyncTask to wait
code:
//preparatory step 1
if (this.mBTAdapter.isEnabled()) {
mATDisableBT = new ATDisableBT();
try {
mATDisableBT.execute().get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
//enable BT.
this.mATEnableBT = new ATEnableBT();
this.mATEnableBT.execute();
You can do this way:
doInBackground of AsyncTask
#Override
protected Void doInBackground(String... params) {
Log.i("doInBackground", "1");
synchronized (this) {
try {
mAsyncTask.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
Log.i("doInBackground", "2");
return null;
}
Outside this function from where you have to nstrong textotify AsyncTask to release from wait state:
new CountDownTimer(2000, 2000) {
#Override
public void onTick(long l) {
}
#Override
public void onFinish() {
synchronized (mAsyncTask) {
mAsyncTask.notify();
}
}
}.start();
Here I have notified AsyncTask by CountDownTimer after 2 seconds.
Hope this will help you.
You should execute AsyncTask on UI thread, so using get() - which will block it makes no sense - it might get you ANR error.
If you are on HONEYCOMB and up, then AsyncTasks are executed on single executor thread, serially - so your mATEnableBT should get executed after mATDisableBT. For more see here:
http://developer.android.com/reference/android/os/AsyncTask.html#execute(Params...)
You might also switch from AsyncTask to Executors. AsyncTask is implemented using executors. By creating single threaded executor you make sure tasks will get executed serially:
ExecutorService executor = Executors.newSingleThreadExecutor();
//...
executor.submit(new Runnable() {
#Override
public void run() {
// your mATDisableBT code
}
});
executor.submit(new Runnable() {
#Override
public void run() {
// your mATEnableBT code
}
});
I have a worker thread and occasionally i send updates to the UI Thread using Handler.Post(). In some cases i need worker thread to wait until Handler.Post() executed on UI Thread and the view is modified and after UI thread is modified, notify the worker Thread to go on...
here is my simple worker thread:
workerThread = new Thread() {
#Override
public void run() {
progressBarHandler.post(new Runnable() {
public void run() {
//Step1: which works ok
ActionModeButton.performClick();
}
}
//Step2: returns null pointer exception because ActionMode
//is not yet created and R.id.select_recording is an
//ActionMode button if I put Thread.sleep(1000); here it
//will work fine.
final View selectRecording = getActivity()
.findViewById(R.id.select_recording);
selectRecording.post(new Runnable() {
public void run() {
selectRecording.performClick();
}
});
}
}
workerThread.start();
using synchronized block with wait and notify
final Handler handler = new Handler();
final Object lock = new Object();
new Thread(new Runnable() {
boolean completed = false;
#Override
public void run() {
handler.post(new Runnable() {
#Override
public void run() {
synchronized (lock) {
//Do some stuff on ui thread
completed = true;
lock.notifyAll();
}
}
});
synchronized (lock) {
try {
if(!completed)
lock.wait();
}
catch (InterruptedException e) {
}
}
}
}).start();
What about using a Semaphore for that?
Semaphore semaphore = new Semaphore(0);
uiHandler.post(new Runnable() {
// ... do something here
semaphore.release();
});
semaphore.acquire();
The Semaphore start with 0 permit. The thread will block on semaphore.acquire() until semaphore.release() (which will add a permit) is called.
I have a very simple UI and i need to constantly run a check process, so I am trying to use a Thread with a while loop.
When I run the loop with nothing but a Thread.sleep(1000) command, it works fine, but as soon as I put in a display.setText(), the program runs for a second on the emulator then quits. I cannot even see the error message since it exits so fast.
I then took the display.setText() command outside the thread and just put it directly inside onCreate, and it works fine (so there is no problem with the actual command).
here is my code, and help will be greatly appreciated.
Thank you!
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
on=(Button) findViewById(R.id.bon);
off=(Button) findViewById(R.id.boff);
display=(TextView) findViewById(R.id.tvdisplay);
display2=(TextView) findViewById(R.id.tvdisplay2);
display3=(TextView) findViewById(R.id.tvdisplay3);
stopper=(Button) findViewById(R.id.stops);
stopper.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(boo=true)
{
boo=false;
display3.setText("System Off");
}
else{
boo=true;
}
}
});
Thread x = new Thread() {
public void run() {
while (boo) {
display3.setText("System On");
try {
// do something here
//display3.setText("System On");
Log.d(TAG, "local Thread sleeping");
Thread.sleep(1000);
} catch (InterruptedException e) {
Log.e(TAG, "local Thread error", e);
}
}
}
};
display3.setText("System On");
display3.setText("System On");
x.start();
}
You can't update the UI from a non-UI thread. Use a Handler. Something like this could work:
// inside onCreate:
final Handler handler = new Handler();
final Runnable updater = new Runnable() {
public void run() {
display3.setText("System On");
}
};
Thread x = new Thread() {
public void run() {
while (boo) {
handler.invokeLater(updater);
try {
// do something here
//display3.setText("System On");
Log.d(TAG, "local Thread sleeping");
Thread.sleep(1000);
} catch (InterruptedException e) {
Log.e(TAG, "local Thread error", e);
}
}
}
};
You could also avoid a Handler for this simple case and just use
while (boo) {
runOnUiThread(updater);
// ...
Alternatively, you could use an AsyncTask instead of your own Thread class and override the onProgressUpdate method.
Not 100% certain, but I think it is a case of not being able to modify UI controls from a thread that did not create them?
When you are not in your UI thread, instead of display3.setText("test") use:
display3.post(new Runnable() {
public void run() {
display3.setText("test");
{
});
You should encapsulate this code in an AsyncTask instead. Like so:
private class MyTask extends AsyncTask<Void, Void, Void> {
private Activity activity;
MyTask(Activity activity){
this.activity = activity;
}
protected Long doInBackground() {
while (true){
activity.runOnUiThread(new Runnable(){
public void run(){
display3.setText("System On");
}
});
try{
Thread.sleep(1000);
}catch (InterruptedException e) {
Log.e(TAG, "local Thread error", e);
}
}
}
Then just launch the task from your onCreate method.
In non-UI thread,you can't update UI.In new Thread,you can use some methods to notice to update UI.
use Handler
use AsyncTask
use LocalBroadcast
if the process is the observer pattern,can use RxJava
I am learning via a book and it gives me this example:
Handler handler=new Handler() {
#Override
public void handleMessage(Message msg) {
bar.incrementProgressBy(5);
}
};
and
Thread background=new Thread(new Runnable() {
public void run() {
try {
for (int i=0;i<20 && isRunning.get();i++) {
Thread.sleep(500);
handler.sendMessage(handler.obtainMessage());
}
} catch (Throwable t) {
// just end the background thread
}
}
});
Which works out great. But, further down in the book it says:
If you would rather not fuss with Message objects, you can also pass
Runnable objects to the Handler, which will run those Runnable
objects on the activity UI thread. ...you can use those same methods
on any View (i.e., any widget or container). This slightly simplifies
your code, in that you can then skip the Handler object.
But there are no examples given of how to do this via a Runnable object. Does anyone have an example?
Something like this:
Handler h = new Handler();
Thread background=new Thread(new Runnable() {
public void run() {
try {
for (int i=0;i<20 && isRunning.get();i++) {
Thread.sleep(500);
handler.post(new Runnable() {
public void run() {
bar.incrementProgressBy(5);
}
});
}
}
catch (Throwable t) {
// just end the background thread
}
}
});
As per the Android Docs for Handler:
public final boolean post (Runnable r)
Since: API Level 1 Causes the Runnable r to be added to the message
queue. The runnable will be run on the thread to which this handler is
attached. Parameters
r -- The Runnable that will be executed. Returns
Returns true if the Runnable was successfully placed in to the message
queue. Returns false on failure, usually because the looper processing
the message queue is exiting.