public abstract class TaskQueue<T> {
private Thread execThread;
private List<T> queue = new LinkedList<T>();
public void addTask(T task) {
queue.add(task);
if (null == execThread || !execThread.isAlive())
loop();
}
public void addALLTask(List<T> tasks) {
queue.addAll(tasks);
if (null == execThread || !execThread.isAlive())
loop();
}
protected void loop() {
(execThread = new Thread() {
@Override
public void run() {
while (!queue.isEmpty()) {
if (isOk(queue.get(0)))
execute(queue.remove(0));
else
queue.add(queue.remove(0));
}
}
}).start();
}
protected abstract void execute(T task);
public void stop(){
queue.clear();
}
public void interrupt(){
execThread.interrupt();
}
protected boolean isOk(T task){
return true;
}
}
使用示例:
public class TaskQueueTest {
private TaskQueue<String> queue = new TaskQueueExample();
private static String[] tasks = { "a", "b", "c", "d" };
private Map<String, String> resources = new HashMap<>();
public static void main(String[] args) {
final TaskQueueTest test = new TaskQueueTest();
for (String t : tasks)
test.queue.addTask(t);
new Thread() {
String[] ks = new String[tasks.length];
int p = 0;
@Override
public void run() {
while (check()) {
double random = Math.random();
String key = null;
if(p != 0)
key = ks[((int) (random * 1000)) % p];//保证只取ks的前p个元素
else
key = ks[0];
test.resources.put(key, random + "");
}
}
public boolean check() {
boolean b = false;
int i;
for (i = -1,p = 0; p < tasks.length; p++) {
if (!test.resources.containsKey(tasks[p])) {
// i=i+1;
ks[++i] = tasks[p];
b = true;
}
}
p = i;
return b;
}
}.start();
}
class TaskQueueExample extends TaskQueue<String> {
@Override
protected void execute(String task) {
System.out.println("task: " + task + " resource:" + resources.get(task));
}
@Override
protected boolean isOk(String task) {
return resources.containsKey(task);
}
}
}