使用场景##
ImageLoaer和网络请求框架中都会使用到此种类型的策略,对队列中的数据进行排序,动态的实现按需加载,当然我们也可以使用双端队列来实现.这里不用双端队列。
来上代码 ###:
public class TmpInfo {
private int taskId;
public TmpInfo(int taskId) {
this.taskId = taskId;
}
public int getTaskId() {
return taskId;
}
public void setTaskId(int taskId) {
this.taskId = taskId;
}
@Override
public String toString() {
return "TmpInfo{" + "taskId=" + taskId + '}';
}
}
Activity中的代码
// 数据集合
private List<TmpInfo> list = new ArrayList<>();
// 加载策略
LoadP loadP = LoadP.SERIIAL;
private ExecutorService executorService = Executors.newCachedThreadPool();
private boolean isRunning = true;
enum LoadP {
// 顺序 // 逆序
SERIIAL, REVERSE
}
// 比较器
Comparator<? super TmpInfo> camp;
@Override
public void initData() {
for (int i = 0; i < 5; i++) {
list.add(new TmpInfo(i + 1));
}
switch (loadP) {
case SERIIAL:
// [ 1,2,3,4,5 ]
camp = new SerialComparator();
break;
case REVERSE:
// [ 5,4,3,2,1 ]
camp = new ReverseComparator();
break;
}
// 使用该种策略,添加之后必须对集合中的数据进行排序
Collections.sort(list, camp);
display();
executorService.execute(() -> {
while (isRunning) {
if (list != null && list.size() > 0) {
TmpInfo t = null;
// 取数据的时候直接从0位置开始移除数据即可
t = list.remove(0);
LogUtils.logE("取到元素:" + t.getTaskId());
}
}
});
}
@Override
protected void onDestroy() {
isRunning = false;
super.onDestroy();
}
private void display() {
if (list == null || list.size() == 0) {
LogUtils.logE("[ ]");
return;
}
StringBuffer sb = new StringBuffer();
for (TmpInfo info : list) {
sb.append(info.getTaskId()).append(",");
}
sb.deleteCharAt(sb.length() - 1);
LogUtils.logE("[ " + sb.toString() + " ]");
}
private class SerialComparator implements Comparator<TmpInfo> {
@Override
public int compare(TmpInfo lhs, TmpInfo rhs) {
// 1-2 = -1 小的有前面
return lhs.getTaskId() - rhs.getTaskId();
}
}
private class ReverseComparator implements Comparator<TmpInfo> {
@Override
public int compare(TmpInfo lhs, TmpInfo rhs) {
// 2-1 = 1, 大的在前面
return rhs.getTaskId() - lhs.getTaskId();
}
}