如何测试创建单独线程的方法?

时间:2016-10-22 19:02:51

标签: java multithreading junit junit4 executorservice

这是我第一次尝试为多线程java程序编写JUnit。

我有一个如下所示的方法,你能否建议我如何为此编写JUnit?或者指出任何类似的例子?非常感谢... !!

public void myMethod(Input input) {
    if (!this.isStreamingPaused()) {
        ExecutorService publisherThreadPool = getThreadPool();
        PublisherThread publisher = new PublisherThread();
        publisher.setInputData(input);
        publisherThreadPool.execute(publisher);
        publisherThreadPool.shutdown();
    }
}

public ExecutorService getThreadPool() {
    final ThreadFactory threadFactory = new BasicThreadFactory.Builder()
                .namingPattern("MyName-%d")
                .priority(Thread.NORM_PRIORITY)
                .build();
    return Executors.newFixedThreadPool(1, threadFactory);
}

1 个答案:

答案 0 :(得分:1)

您可以尝试使用java.util.concurrent.CountDownLatch

public void myMethod(Input input) {
    if (!this.isStreamingPaused()) {
        ExecutorService publisherThreadPool = getThreadPool();

        // in case that you'd have more of the same kind of operations to do
        // you can use appropriately a higher count than 1
        CountDownLatch  latch = new CountDownLatch(1);

        PublisherThread publisher = new PublisherThread();
        publisher.setInputData(input);
        publisherThreadPool.execute(publisher);
        publisherThreadPool.shutdown();


        try {
            latch.await();
        } catch (InterruptedException e) {
            LOG.info("Interrupted by another thread");
        } 
    }
}

PublisherThread课程中,您可以执行以下更改:

private CountDownLatch latch;

public PublisherThread(CountDownLatch latch){
    this.latch = latch;
}

public void run(){
  try{
      // kafka business logic
      // ....
  } finally {
      // you don't want your program to hang in case of an exception 
      // in your business logic
      latch.countDown();
  }
}