诀窍是使用固定的队列大小和:
new ThreadPoolExecutor.CallerRunsPolicy()
我也建议使用Guava的ListeningExecutorService。
这是消费者/生产者队列的示例。
private ListeningExecutorService producerExecutorService = MoreExecutors.listeningDecorator(newFixedThreadPoolWithQueueSize(5, 20));
private ListeningExecutorService consumerExecutorService = MoreExecutors.listeningDecorator(newFixedThreadPoolWithQueueSize(5, 20));
private static ExecutorService newFixedThreadPoolWithQueueSize(int nThreads, int queueSize) {
return new ThreadPoolExecutor(nThreads, nThreads,
5000L, TimeUnit.MILLISECONDS,
new ArrayBlockingQueue(queueSize, true), new ThreadPoolExecutor.CallerRunsPolicy());
}
任何更好的东西,你可能想考虑像RabbitMQ或ActiveMQ一样的MQ,因为他们有QoS技术。
如果觉得《java 过载_java – ExecutorService 避免任务队列过载的标准方式》对你有帮助,请点赞、收藏,并留下你的观点哦!