[原创]java延时处理队列

之前在做.net开发需要延时处理的时候会调用ThreadPool.RegisterWaitForSingleObject,最近做java的时候做了个延迟处理队列,代码如下:
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class DelayProcessQueue<T> {
private final Queue<T> queue = new LinkedList<T>();
private final List<DelayProcessor> processors = new ArrayList<DelayProcessor>();
private final Thread workThread = new Thread(new ProcessWorkClass());
private final ScheduledThreadPoolExecutor delayExecutor = new ScheduledThreadPoolExecutor(10);

public DelayProcessQueue(){
this(null);
}

public DelayProcessQueue(List<DelayProcessor> processors){
if(processors != null)
this.processors.addAll(processors);

workThread.setName("DelayProcessQueueThread");
workThread.setDaemon(true);
workThread.start();
}

public void registerProcessor(DelayProcessor processor){
this.processors.add(processor);
}

public void enQueue(T item) throws Exception{
if(processors.isEmpty())
throw new Exception("no processor has registered!");
queue.add(item);
}

class ProcessWorkClass implements Runnable{

@Override
public void run() {
// TODO Auto-generated method stub
while(true){
if(queue.isEmpty())
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

T item = queue.poll();
if(item == null)
continue;

for(DelayProcessor p : processors){
if(p.checkNeedProcess(item)){
delayExecutor.schedule(p.getProcessor(item), p.getDelayMillisecond(), TimeUnit.MILLISECONDS);
}
}
}
}
}
}


public abstract class DelayProcessor<T>{
private int delayMillisecond = 1;

public abstract void process(T args);

public abstract boolean checkNeedProcess(T args);

public Runnable getProcessor(T args){
return new RealProcessor(args);
}

public int getDelayMillisecond() {
return delayMillisecond;
}

public void setDelayMillisecond(int millisecond) {
this.delayMillisecond = millisecond;
}

public class RealProcessor implements Runnable{
private T args;

public RealProcessor(T args){
this.args = args;
}

@Override
public void run() {
// TODO Auto-generated method stub
process(args);
}
}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值