You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java技术问询:该JUnit测试中的方法是否为多线程实现?

Is This a Multi-Threaded Implementation?

No, this code does not implement multi-threading. Here’s why:

  • You’ve defined a Runnable class, but you’re calling its run() method directly instead of launching it in a new thread. When you invoke run() like this (new runnableClass().run();), the code inside run() executes synchronously in the same thread as your test method—no new thread is created at all.

To turn this into a proper multi-threaded implementation, you need to wrap your Runnable in a Thread instance and call start() instead of run(). Here’s the corrected version:

@Test 
public void generate___() { 
    long startTime = System.nanoTime(); 
    // Keep track of threads to wait for completion (optional but recommended)
    List<Thread> threads = new ArrayList<>();
    
    for (File file : getResultsFromFolder("C:\\temp\\....")) { 
        class runnableClass implements Runnable{ 
            public void run() { 
                // do something with file 
            } 
        } 
        // Create a new Thread and start it
        Thread thread = new Thread(new runnableClass());
        thread.start();
        threads.add(thread);
    } 
    
    // Wait for all threads to finish before calculating total time
    for (Thread thread : threads) {
        try {
            thread.join();
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            e.printStackTrace();
        }
    }
    
    long endTime = System.nanoTime(); 
    System.out.println("total took: " + (endTime - startTime) / 1000000);
}

A quick note on the added thread tracking: If you don’t use join(), your endTime will be logged immediately after starting all threads, not after they finish their work. This gives you an accurate total runtime for all tasks.

内容的提问来源于stack exchange,提问作者Allen H.

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 07:02:52