public class TaskManager {
private TaskManager(){
}
private final static TaskManager instance = new TaskManager();
public static TaskManager getInstance(){
return instance;
}
private ExecutorService executor = null;
private ConcurrentLinkedQueue<BaseTask> taskQueue = new ConcurrentLinkedQueue<BaseTask>();
private TaskExecutor taskExecutor;
public void addTask(BaseTask task){
taskQueue.add(task);
taskExecutor.notifyTaskAdded();
}
public BaseTask popTask(){
return taskQueue.poll();
}
public int getTaskSize(){
return taskQueue.size();
}
public void startService(){
executor = Executors.newFixedThreadPool(1);
taskExecutor = new TaskExecutor();
executor.execute(taskExecutor);
}
public void stopService(){
}
}
public class TaskExecutor implements Runnable{
private boolean isStarted = true;
private Object obj = new Object();
@Override
public void run() {
while(isStarted){
int taskSize = TaskManager.getInstance().getTaskSize();
synchronized(obj){
if(taskSize == 0){
try {
LogUtil.logDebug("There is no task to execute now, waiting...");
obj.wait();
} catch (InterruptedException e) {
}
}
}
BaseTask task = TaskManager.getInstance().popTask();
if(task != null){
LogUtil.logDebug("execute one task...");
task.run();
}
}
}
public void notifyTaskAdded(){
synchronized(obj){
obj.notify();
}
}
public void stop(){
this.isStarted = false;
}
}