我正在编写一个同时执行多个线程的程序(并行),我使用的是TaskExecutor。
@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");
}
当我测试我的代码时,引发了AssertionError异常。我正在使用Spring Framework来管理执行。
这是日志屏幕:
Exception in thread "main" java.lang.AssertionError
at org.junit.Assert.fail(Assert.java:92)
at org.junit.Assert.assertTrue(Assert.java:43)
at org.junit.Assert.assertNotNull(Assert.java:526)
任何人都有任何想法请:)谢谢
答案 0 :(得分:1)
我找到了解决方案,我必须初始化threadPoolTaskExecutor所以当我们使用assertNotNull(threadPoolTaskExecutor)时;该对象将被初始化,我们可以执行我们的线程。
这是initialize方法:
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);
}
这里是executorService定义:
private ThreadPoolExecutor executorService;
感谢Andrew,Pace和Ingo的帮助:)