Java 使用TaskExecutor时的AssertionError
我正在编写一个同时(并行)执行多个线程的程序,我正在使用TaskExecutorJava 使用TaskExecutor时的AssertionError,java,multithreading,spring,junit4,Java,Multithreading,Spring,Junit4,我正在编写一个同时(并行)执行多个线程的程序,我正在使用TaskExecutor @Autowired TaskExecutor threadPoolTaskExecutor; @Test public void testSpringTaskExecutor() throws InterruptedException { assertNotNull(threadPoolTaskExecutor); for (int k =
@Autowired TaskExecutor threadPoolTaskExecutor;
@Test
public void testSpringTaskExecutor()
throws InterruptedException {
assertNotNull(threadPoolTaskExecutor);
for (int k = 0; k < 5; k++) {
Runnable myThread =
new Workflow(new AtomicInteger(k));
threadPoolTaskExecutor.execute(myThread);
}
Thread.sleep(500);
logger.info("Finished all threads");
}
任何人有任何想法请:)谢谢我找到了解决方案,我必须初始化threadPoolTaskExecutor,因此当我们使用assertNotNull(threadPoolTaskExecutor)时;对象将被初始化,我们可以执行线程 以下是初始化方法:
public void initialize() {
logger.info("Creating ThreadPoolExecutor");
BlockingQueue queue = createQueue(this.queueCapacity);
executorService = new ThreadPoolExecutor (
this.corePoolSize, this.maxPoolSize, this.keepAliveSeconds, TimeUnit.SECONDS,
queue, this.threadFactory, this.rejectedExecutionHandler);
}
以下是Executor服务定义:
private ThreadPoolExecutor executorService;
感谢安德鲁、佩斯和英戈的帮助:)你期待什么?您在哪里初始化线程池任务执行器?实现testSpringTaskExecutor方法的类继承自另一个类,该类从配置文件@ContextConfiguration(classes={JavaConfigurator.class})获取上下文,我使用的是注释@Autowired ApplicationContext sprinCtx;这一切都很好,但显然这并没有初始化它,对吗?不,我不能从父类获取上下文,这就是问题所在,@Autowired会这样做,但它不起作用。看起来threadPoolTaskExecutor是包作用域。您的父类在同一个包中吗?如果有公共的getter/setter方法,它是否工作得更好?
private ThreadPoolExecutor executorService;