Using Junit to test a Runnable method , the logic inside of a for loop unexpectedly execute only once

Viewed 280

I am learning Threading in Java and use the demo code inside this video;

https://www.youtube.com/watch?v=Xj1uYKa8rIw

Instead of writing a standalone Java program, I do it inside a jUnit test.

In the demo, there are two classes, each with a run method and a for loop inside, and there is a sleep command inside the for loop.

What I expect is that it will do 5 System.out.println inside the loop, with 0.5 sec waiting in between each output ;

However, the logic inside the for loop iteration only do once. enter image description here I tried removing Thread.currentthread().sleep(500), then it works as expected.

Please kindly let me know why it behave like that by putting the Thread.currentThread().sleep method and how shall I fix it so that it will iterate as expected.

Below is the testing code snipplet:

import org.junit.jupiter.api.Test;

public class TheadTest {
 

    @Test
    void Threadtest2() {
        Hi hi = new Hi();
        Hello hello = new Hello();
        Thread t1 = new Thread(hi);
        Thread t2 = new Thread(hello);
        t1.start();
        t2.start();
    }
}

class Hi implements Runnable {

    public void runx() {

    }

    public void run() {
        for (int i = 0; i < 5; i++) {
            System.out.println("HI");
            System.out.println(i);
            try {
                // Thread.sleep(500);
                Thread.currentThread().sleep(500);
            } catch (InterruptedException e) {
             
                e.printStackTrace();
            }
        }
    }
}

class Hello implements Runnable {
    public void runx() {

    }

    public void run() {
        for (int j = 0; j < 5; j++) {
            System.out.println("Hello");
            try {
                System.out.println(j);
                Thread.currentThread().sleep(500);
             
            } catch (InterruptedException e) {
             
                e.printStackTrace();
            }
        }
    }
}
1 Answers

This is happening because your main/daemon "JUnit" thread is not waiting for other threads to complete.

Adding explicit wait for two threads:

@Test
    void Threadtest2() {
        Hi hi = new Hi();
        Hello hello = new Hello();
        Thread t1 = new Thread(hi);
        Thread t2 = new Thread(hello);
        t1.start();
        t2.start();
        t1.join();
        t2.join(); 
    }
Related