Java Embedded Objects in ExecutorService

I have a single ExecutorService thread object. In the future, in the future, tasks will be added using the submit () method. My understanding is that submit will present the added submitted Runnable at the end of the list of tasks to be completed. However, I have a situation where, based on the logical, I can send runnable to the beginning of the tasks that will be performed. I do not want this to affect the current task, so the next task will be the one I just gave. A sample example is reproduced below. How to do it?

thank

private ExecutorService singleLoadPool = Executors.newSingleThreadExecutor();
public void submitTask(Runnable run, boolean doNow) {
    if (doNow)
        singleLoadPool.submitFront(run);  // This is the method I'm looking for
    else
        singleLoadPool.submit(run);
}
+5
source share
2 answers

LinkedBlockingDeque. / - putFirst(e)/takeFirst() putLast(e)/takeLast() - - Comparator . - , OutOfMemoryError.

edit :

-, ExecutorService

ExecutorService executorService = new ThreadPoolExecutor(1, 1, 1, TimeUnit.SECONDS, workQueue);

-, : workQueue?

workQueue BlockingQueue, LinkedBlockingDeque, , offer(), ThreadPoolExecutor , :

       public boolean offer(E e) {
       if(doNow)
         return linkedBlockingDequeInstance.offerFirst(e);
      else 
         return linkedBlockingDequeInstance.offerLast(e);
   }

, - , . , .

+4

, ThreadPoolExecutor PriorityBlockingQueue. , PriorityBlockingQueue, Comparator. Comparator , "".

PriorityBlockingQueue<Runnable> workQueue = new PriorityBlockingQueue<Runnable>(20, yourPriorityComparator);
ExecutorService executorService = new ThreadPoolExecutor(1, 1, 1, TimeUnit.SECONDS, workQueue);
+1

All Articles