特点: 队列中有优先级比较的线程池
使用案例:
val pool: ExecutorService = ThreadPoolExecutor(
3,
3,
0,
TimeUnit.SECONDS,
PriorityBlockingQueue<Runnable>()
)
复制代码
暂时先用java写着
public abstract class PriorityRunnable implements RUnnable, Comparable<PriorityRunnable> {
private int priority;
public PriorityRunnable(int priority) {
if (priority < 0) {
throw new IllegalArgumentException();
}
this.priority = priority;
}
public int getPriority() {
return priority;
}
@Override
public int compareTo(@NonNull PriorityRUnnable another) {
int me = this.priority;
int anotherPri = another.getPriority();
return me == anotherPri ? 0 : me < anotherPri ? 1 : -1;
}
@override
public void run() {
doSomeThing();
}
protected abstract void doSomeThing();
}
复制代码
txt.click {
for (i in 0..99) {
val priority = i
pool.execute(object: PriorityRunnable(priority) {
override doSomeThing() {
log("优先级${proiority}的任务被执行")
try {
Thread.sleep(2000)
}catch (e: Exception) {
e.printStackTrace()
}
}
})
}
}
复制代码