2013-03-21 44 views
2

我正在寫一個程序,在同一時間(並行)執行多個線程,我正在使用TaskExecutor。AssertionError當使用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 exeption。我正在使用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) 

任何一個有任何想法,請:)謝謝

+1

你是怎麼想到?你在哪裏初始化了線程池任務執行器? – Ingo 2013-03-21 09:58:16

+0

實現testSpringTaskExecutor方法的類繼承自另一個從配置文件@ContextConfiguration(classes = {JavaConfigurator.class}) 獲取上下文的類,並且我使用了註釋@Autowired ApplicationContext sprinCtx; – 2013-03-21 10:02:12

+0

這一切都很好,但顯然這並沒有初始化它,是嗎? – Ingo 2013-03-21 10:07:56

回答

1

我找到了解決辦法,我必須初始化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; 

謝謝安德魯和佩斯和英戈對你有所幫助:)