You can use Thread.join()
to prevent the test from finishing before the new thread has completed its task:
@org.junit.Test
public void TestThreads() throws InterruptedException {
Thread t = new Thread(new Runnable() {
public void run() {
for (int i = 1; i < 1000; i++) System.out.println(i);
}
});
t.start();
t.join();
}
Normally, the JVM will terminate when the last non-daemon thread terminates. You might expect that simply calling t.setDaemon(false)
on the thread would prevent the JVM from exiting before the task is finished. However, junit will call System.exit() when the main thread has finished.
As Gus notes in the comments: "you need join() because start() doesn't block".
He's correct that you could also call run()
in this minimal example. However, I assume you're starting a thread because you want it to run concurrently with another thread. Calling run()
on a Thread is flagged up as a possible mistake by FindBugs - if you're just going to call run()
, you'd probably just want to implement Runnable instead of using Thread.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…