在线程池中的某一任务完成后,我们不知道新的任务已经到达等待处理,这时候就要加入工作队列的原理了。就线程池里面而言,分为许多工作队列等待我们去处理任务,这里需要我们对这些队列有一个初步的掌握。下面我们就线程池工作队列概念进行讲解,然后带来几种常见的队伍进行分享。
1.工作队列概念
通常想要的是同一组固定的工作线程相结合的工作队列,它使用 wait() 和 notify() 来通知等待线程新的工作已经到达了。该工作队列通常被实现成具有相关监视器对象的某种链表。尽管 Thread API 没有对使用Runnable 接口强加特殊要求,但使用 Runnable 对象队列的这种模式是调度程序和工作队列的公共约定。
publicclassWorkQueue
{
privatefinalintnThreads;
privatefinalPoolWorker[]threads;
privatefinalLinkedListqueue;
publicWorkQueue(intnThreads)
{
this.nThreads=nThreads;
queue=newLinkedList();
threads=newPoolWorker[nThreads];
for(inti=0;i<nThreads;i++){
threads[i]=newPoolWorker();
threads[i].start();
}
}
publicvoidexecute(Runnabler){
synchronized(queue){
queue.addLast(r);
queue.notify();
}
}
privateclassPoolWorkerextendsThread{
publicvoidrun(){
Runnabler;
while(true){
synchronized(queue){
while(queue.isEmpty()){
try
{
queue.wait();
}
catch(InterruptedExceptionignored)
{
}
}
r=(Runnable)queue.removeFirst();
}
//Ifwedon'tcatchRuntimeException,
//thepoolcouldleakthreads
try{
r.run();
}
catch(RuntimeExceptione){
//Youmightwanttologsomethinghere
}
}
}
}
2.工作队列种类
(1)ArrayBlockingQueue
ArrayBlockingQueue(有界队列)是一个用数组实现的有界阻塞队列,按FIFO排序量。
(2)LinkedBlockingQueue
LinkedBlockingQueue(可设置容量队列)基于链表结构的阻塞队列,按FIFO排序任务,容量可以选择进行设置,不设置的话,将是一个无边界的阻塞队列,长度为Integer.MAX_VALUE,吞吐量通常要高于ArrayBlockingQuene;newFixedThreadPool线程池使用了这个队列
(3)DelayQueue
DelayQueue(延迟队列)是一个任务定时周期的延迟执行的队列。根据指定的执行时间从小到大排序,否则根据插入到队列的先后排序。newScheduledThreadPool线程池使用了这个队列。
原文来自:https://www.py.cn


















































暂无评论内容