轻量级任务队列

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);
		}

	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值