简体   繁体   English

Java线程池阻塞队列,总是执行最后几个

[英]Java thread pool blocking queue, execute always last few

I have several tasks that are being created by some event. 我有几个由某个事件创建的任务。 I want to execute the last few tasks(suppose 6) always. 我想总是执行最后几个任务(假设6)。

I am using a fixed thread pool. 我正在使用固定的线程池。 But the problem I am facing is that, it uses a blocking queue internally. 但我面临的问题是,它在内部使用阻塞队列。 I want to dequeue the tasks from the blocking queue if there are new tasks coming in, without pushing them to the executor. 如果有新任务进入,我想从阻塞队列中将任务出列,而不是将它们推送到执行程序。 How can I achieve this? 我怎样才能做到这一点? Is there a different approach to this problem? 这个问题有不同的方法吗?

In order to do what you want, you can use a ScheduledThreadPoolExecutor . 为了做你想做的事,你可以使用ScheduledThreadPoolExecutor And set the flag setRemoveOnCancelPolicy(true) . 并设置标志setRemoveOnCancelPolicy(true)

This executor returns a Future when you call the submit methods. 当您调用submit方法时,此执行程序返回Future These futures have a cancel() method that you can call when the new request comes in. You can even cancel the tasks that are currently running if you want too. 这些期货有一个cancel()方法,您可以在新请求进入时调用。您甚至可以取消当前正在运行的任务。

There's another alternative to call ThreadPoolExecutor.getQueue().clear() , but this is not safe! 还有另一种方法可以调用ThreadPoolExecutor.getQueue().clear() ,但这不安全! So please don't try it :) 所以请不要尝试:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM