我在我的应用程序中实现了chating并尝试实现调度机制。如果用户没有互联网连接,则会将其置于预定队列中。
我有一个线程执行器
private ExecutorService executor = Executors.newSingleThreadExecutor();
并为我的任务设置一个计划程序
public class MessageScheduler {
private ConcurrentLinkedQueue<MessageTask> queue;
public MessageScheduler() {
queue = new ConcurrentLinkedQueue<>();
}
public void schedule(MessageTask messageTask) {
queue.add(messageTask);
}
public ArrayList<MessageTask> getScheduled() {
return new ArrayList<>(queue);
}
public boolean isEmpty() {
return queue.isEmpty();
}
public MessageTask pop() {
return queue.peek();
}
public void removeHead() {
queue.poll();
}
}
MessageTask有完整的监听器:
public interface OnMessageCompleteListener {
public void onMessageSendingComplete(MessageTask task);
public void onMessageSendingError(MessageTask task);
}
在MessageTask中,我通知侦听器我完成的任务:
@Override
public void run() {
// Async call
listener.onMessageSendingComplete(thisInstance);
}
我的问题是当我通过onMessageSendingComplete()
通知听众时,我需要以相同的方法执行预定的messageTasks:
@Override
public void onMessageSendingComplete(MessageTask task) {
scheduler.removeHead();
if(!scheduler.isEmpty()){
MessageTask readyToExecute = scheduler.pop();
// MessageTask may be not finished already.
// and executor was always will be busy or not?
execute(readyToExecute);
}
}
执行方法:
public void execute(MessageTask messageTask) {
if (!executorIsBusy && isNetworkAvailable) {
messageTask.setOnCompleteListener(this);
executor.execute(messageTask);
executorIsBusy = true;
} else {
scheduler.schedule(messageTask);
}
}
我需要将executorIsBusy
设置为 false ,ExecutorService
是否可以执行?
经过一番思考后,我找到了解决方案。
我改变了
@Override
public void onMessageSendingComplete(MessageTask task) {
scheduler.removeHead();
if(!scheduler.isEmpty()){
MessageTask readyToExecute = scheduler.pop();
// MessageTask may be not finished already.
// and executor was always will be busy or not?
execute(readyToExecute);
}
}
到
@Override
public void onMessageSendingComplete(MessageTask task) {
scheduler.removeHead();
if(!scheduler.isEmpty()){
MessageTask readyToExecute = scheduler.pop();
readyToExecute.setOnCompleteListener(this);
executor.execute(readyToExecute);
} else {
executorIsBusy = false;
}
}