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

Java 如何测试创建单独线程的方法?,java,multithreading,junit,junit4,executorservice,Java,Multithreading,Junit,Junit4,Executorservice,这是我第一次尝试为多线程java程序编写JUnit 我有一个如下所示的方法,你能建议我如何为此编写JUnit吗?或者举出类似的例子?提前多谢 public void myMethod(Input input) { if (!this.isStreamingPaused()) { ExecutorService publisherThreadPool = getThreadPool(); PublisherThread publisher = new Pub

这是我第一次尝试为多线程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);
}

您可以尝试使用
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");
        } 
    }
}
publisherRead
类中,您可以执行以下更改:

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();
  }
}

分开你的顾虑。顾名思义,单元测试应该以功能单元为目标。请对生成线程的类进行一次测试,并对线程类本身进行第二次测试。感谢EJK的回复。我将为PublisherRead线程中的主要功能编写单独的junit,但我在这里关心的是如何测试myMethod中生成线程的代码块?请注意,这样创建线程池意味着不能多次执行
myMethod
。您可能还想检查执行器是否已关闭,并在这种情况下创建一个新实例。为什么
publisherReadPool.shutdown()
execute
知道
getThreadPool()
返回相同的实例后,您将无法调用
myMethod
两次,这是您想要的吗?是的,在1个线程结束之前,myMethod不会执行多次。这段代码的编写方式是,任何时候只有一个线程应该发布数据。如果在线程已经运行并发布(单个或多个数据)数据时,有另一条数据记录准备发布,那么它会将数据写入队列/缓冲区。