java - 使用 TaskExecutor 时出现 AssertionError

标签 java multithreading spring junit4

我正在编写一个同时(并行)执行多个线程的程序,我正在使用 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)

请有任何想法:) 谢谢

最佳答案

我找到了解决方案,我必须初始化 threadPoolTask​​Executor 所以当我们使用 assertNotNull(threadPoolTask​​Executor);该对象将被初始化,我们可以执行我们的线程。

这是初始化方法:

 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/

相关文章:

java - 如何从 jruby 调用 java 静态方法

java - Spring Boot |使用动态 keystore /信任库

java - Java多线程问题: How to clear last element in a list when update method is no longer called?

.net - 检查当前线程是否拥有锁

spring - Grails 插件引用丢弃的同名自定义服务

java - 在 Android 中访问字符串数组中的最后一个 "number"元素

java - Array.newInstance() 是如何工作的?

java - 关键部分: be sure that this method is executed by only 1 thread

spring - 如何在一个应用程序中将tomcat配置成两个不同的域?

java - AnnotationSessionFactoryBean 的问题