I'd like to have a queue of work/tasks to be done on a separate thread, but can only process one work at a time. So not simultaneously.
Is there something built-in android for this?
Thanks,
EDIT: The work = get information from Database. Once done, update the UI with the fetched information.
No, your program would not be multithreading unless you specifically told it to. And in Android's case AsyncTask would be the route to go when interacting with the UIThread (main).
android.os.MessageQueue. Low-level class holding the list of messages to be dispatched by a Looper . Messages are not added directly to a MessageQueue, but rather through Handler objects associated with the Looper. You can retrieve the MessageQueue for the current thread with Looper. myQueue() .
When an application component starts and the application does not have any other components running, the Android system starts a new Linux process for the application with a single thread of execution. By default, all components of the same application run in the same process and thread (called the "main" thread).
In this case, to update the UI from a background thread, you can create a handler attached to the UI thread, and then post an action as a Runnable : Handler handler = new Handler(Looper. getMainLooper()); handler. post(new Runnable() { @Override public void run() { // update the ui from here } });
Have you checked out java.util.concurrent.Executors ? You could do something like this:
final static ExecutorService tpe = Executors.newSingleThreadExecutor();
...
tpe.submit(new Runnable() {
@Override
public void run() {
// your work
}
}):
It's not android specific, it is part of the jdk5.
From the doc:
Creates an Executor that uses a single worker thread operating off an unbounded queue. (Note however that if this single thread terminates due to a failure during execution prior to shutdown, a new one will take its place if needed to execute subsequent tasks.) Tasks are guaranteed to execute sequentially, and no more than one task will be active at any given time. Unlike the otherwise equivalent newFixedThreadPool(1) the returned executor is guaranteed not to be reconfigurable to use additional threads.
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