我正在尝试实现一个可执行的 Runnable 队列,以便在异步任务期间按顺序执行(即下一个在队列中的 Runnable 将在前一个完成后执行)。我编写了一个 Manager 来管理这些可运行任务和任务本身是一个可运行的。然后我获取异步任务中的第一个任务并运行它,希望它会通过队列运行,但它最终只会运行第一个可运行任务两次。有人能够帮助我审查一下我已经编写的代码或者指导一下我类似问题的示例吗?
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);
}