Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android thread queue

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.

like image 656
pdiddy Avatar asked Dec 05 '11 17:12

pdiddy


People also ask

Is Android multithreaded?

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).

What is a MessageQueue in Android?

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() .

Is Android single threaded?

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).

How do threads work in Android?

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 } });


1 Answers

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.

like image 175
gwvatieri Avatar answered Oct 19 '22 23:10

gwvatieri