How to implement a runnables queue

I am trying to implement a queue of executable files that will be executed one after another (which means that the next queue will be executed after the completion of another) during an asynchronous task. I wrote a dispatcher to manage these runnables and the task that is the most runnable. Then I get the first task in the asynchronous task and run it in the hope that it will work through the queue, however, it just finishes launching the first run twice. Can someone help me with the code I worked with, or give me an example that might be useful?

public class ConnectionManager {

    public static final int MAX_CONNECTIONS = 15;

    private ArrayList<Runnable> active = new ArrayList<Runnable>();
    private ArrayList<Runnable> queue = new ArrayList<Runnable>();

    private static ConnectionManager instance;

    public static ConnectionManager getInstance() {
        if (instance == null)
            instance = new ConnectionManager();
        return instance;
    }

    public void push(Runnable runnable) {
        queue.add(runnable);
        if (active.size() < MAX_CONNECTIONS)
            startNext();
    }

    private void startNext() {
        if (!queue.isEmpty()) {
            Runnable next = queue.get(0);
            queue.remove(0);
            active.add(next);

            Thread thread = new Thread(next);
            thread.start();
        }
    }

    public void didComplete(Runnable runnable) {
        active.remove(runnable);
        startNext();
    }
}

public class Task implements Runnable {
    Context con;
    String xmlFile;
    File taskFile;
    String Id;

    public void create(Context context, String xml, File task, String id) {
        this.con = context;
        this.xmlFile = xml;
        this.taskFile = task;
        this.Id = id;
        ConnectionManager.getInstance().push(this);
    }

    @Override
    public void run() {
        User.SendTask(con, xmlFile, taskFile, Id);

        ConnectionManager.getInstance().didComplete(this);
    }
+5
source share
5 answers

- , , , , , , . AsyncTask ( , ... mgmt), doInBackground , , onPostExecute.

+2

, ThreadPoolExecutor, . minPool 1 15, .

+2

Queue ArrayLists? .

+2

ArrayList , . , , . , , :

  • push runnables. add , , , , .

  • Then StartNext is called a bunch of times at the same time. One of the threads runs "next = queue.Get (), however the other thread also calls" next = queue.Get () "before the first thread has the ability to remove this item from the queue, so both threads complete the same runnable.

You will need to either find the thread safety object to use, or add some mutex / locking mechanism to ensure that different threads do not work with each other.

+1
source

All Articles