我正在编写一个同时(并行)执行多个线程的程序,我正在使用 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 框架来管理执行。
这是日志屏幕:
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)
请有任何想法:) 谢谢
最佳答案
我找到了解决方案,我必须初始化 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);
}
这里是 executorService 定义:
private ThreadPoolExecutor executorService;
谢谢 Andrew、Pace 和 Ingo 的帮助:)
关于java - 使用 TaskExecutor 时出现 AssertionError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15544213/