【发布时间】:2016-10-27 19:37:23
【问题描述】:
目前,我们的一个应用中有 2 个线程池:
- 第一个是用来处理定时任务的
- 第二个处理正在运行的每个计划任务的并行处理
需要设置两个不同的池来自以下想法:如果多个计划任务在主(第一个)池中排队并且它在同一个池中触发它的子任务(并行处理),这将导致竞争条件 as 也会在其他计划任务“后面”排队,因此实际上什么都不会结束并且会发生死锁。
如果子任务的优先级高于计划任务怎么办?他们会“跳过”队列并暂停计划任务以完成吗?或者这不会发生?有没有办法强迫这种行为?或者当 ThreadPoolExecutor 已经在运行任务时不能暂停它们?
池 1 在 Spring 的应用程序上下文 XML 配置文件中定义为:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:task="http://www.springframework.org/schema/task" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/task
http://www.springframework.org/schema/task/spring-task-3.0.xsd">
<context:annotation-config />
<context:component-scan base-package="cl.waypoint.mailer.reportes" />
<task:annotation-driven scheduler="myScheduler" />
<task:scheduler id="myScheduler" pool-size="2" />
<aop:aspectj-autoproxy />
</beans>
Pool 2 在代码中定义如下:
public static ThreadPoolExecutor executor = new ThreadPoolExecutor(10, 10, 30, TimeUnit.SECONDS,
new LinkedBlockingDeque<Runnable>(), new ThreadFactory() {
final AtomicLong count = new AtomicLong(0);
private String namePreffix = "TempAndDoor";
@Override
public Thread newThread(Runnable r) {
Thread t = new Thread(r);
t.setDaemon(false);
t.setPriority(Thread.NORM_PRIORITY);
t.setName(MessageFormat.format("{0}-{1}", namePreffix, count.getAndIncrement()));
return t;
}
});
【问题讨论】:
-
“处理计划任务”和“运行计划任务”有什么区别?
-
@Kayaman 你问这两个池之间的区别?实际上两个池都运行任务,但第二个池为第一个池中的任务运行子任务,这样解释更好吗?
-
添加代码以便我们了解您是如何使用线程池的(顺便问一下,它们是如何配置的?固定线程池?fork join pool?)
-
@GonzaloVasquez 是的,这是一个更好的解释。您可能希望显示一些代码以更清楚地了解您拥有哪些类型的队列等。
-
@LuisRamirez-Monterosa 我刚刚添加了池定义
标签: java multithreading threadpool priority-queue thread-priority