I think the problem you have is that the child threads are being closed sooner than you expected because the main thread(the test itself) reaches to the end.
Remember that when you do a Thread.start() an asynchronous call starts, then if you are running your tests using Junit the execution will continue after this call until the end of the test, and as soon as it reaches to the end, it shutdowns the threads you started inside it.
Therefore, if you have something like:
01. import org.junit.Assert;
02. import org.junit.Test;
03. public class ThreadTest {
04. static boolean didIGetIt = false;
05. @Test
06. public void testThread() {
07. Thread myThread = new Thread(new Runnable() {
08. @Override
09. public void run() {
10. System.out.println("I am an asynchronous task");
11. System.out.println("and JUnit won't wait for me to finish my job!");
12. didIGetIt = true;
13. }
14. });
15. myThread.start();
16. Assert.assertTrue(didIGetIt);
17. }
18. }
It will execute the Assert before the code inside the run() leading to a fail test.
But if you add a simple sleep you could stop the main thread and debug and do what you need before the main thread stops.
01. import org.junit.Assert;
02. import org.junit.Test;
03. public class ThreadTest {
04. static boolean didIGetIt = false;
05. @Test
06. public void testThread() throws InterruptedException {
07. Thread myThread = new Thread(new Runnable() {
08. @Override
09. public void run() {
10. System.out.println("I am an asynchronous task");
11. System.out.println("and JUnit won't wait for me to finish my job!");
12. didIGetIt = true;
13. }
14. });
15. myThread.start();
16. System.out.println("Let's wait for child threads to finish");
17. Thread.sleep(5000);
18. Assert.assertTrue(didIGetIt);
19. }
20. }
Surely there are better ways to do it, but the Thread.sleep may be what you are looking for.
Hope it may help somebody!