Java技术问询:该JUnit测试中的方法是否为多线程实现?
Is This a Multi-Threaded Implementation?
No, this code does not implement multi-threading. Here’s why:
- You’ve defined a
Runnableclass, but you’re calling itsrun()method directly instead of launching it in a new thread. When you invokerun()like this (new runnableClass().run();), the code insiderun()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.
相关产品推荐
相关产品推荐

