java(标准或第三方库)中是否存在一些数据结构,如阻塞队列,可以存储某些任务,每次只接收N个任务。
例如:
答案 0 :(得分:0)
您似乎可以使用DelayQueue:
Delayed元素的无界阻塞队列,其中包含一个元素 只有在延迟到期时才能采取。
类似的东西:
public static void main(String[] args) throws InterruptedException {
final int tasksPerInterval = 3;
final int totalTasks = 50;
final int intervalTime = 2;
final TimeUnit intervalTimeUnit = TimeUnit.SECONDS;
DelayQueue<MyRequest> queue = new DelayQueue <>();
for (int i=0, delayTime=0; i<totalTasks/tasksPerInterval; i++){
for (int j=0; j<tasksPerInterval; j++){
queue.offer(new MyRequest<>(i + "-" + j, intervalTimeUnit, delayTime));
}
delayTime += intervalTime;
}
while (!queue.isEmpty())
System.out.println(queue.take());
}
static class MyRequest <E> implements Delayed {
private E data;
private long startTime;
MyRequest(E data, TimeUnit timeUnit, long delay) {
this.data = data;
this.startTime = System.currentTimeMillis() + TimeUnit.MILLISECONDS.convert(delay, timeUnit);
}
@Override
public long getDelay(TimeUnit unit) {
long diff = startTime - System.currentTimeMillis();
return unit.convert(diff, TimeUnit.MILLISECONDS);
}
@Override
public int compareTo(Delayed o) {
if (this.startTime < ((MyRequest) o).startTime) {
return -1;
}
if (this.startTime > ((MyRequest) o).startTime) {
return 1;
}
return 0;
}
@Override
public String toString() {
return data.toString();
}
}
另请参阅以下question/answers。