0

I'm completely new into MultiThreading and I'm trying to test code in which there is thread.sleep, long story short it looks like this:

private class DemoRunnable implements Runnable {

    private Thread t;

    String status;

    public void start() {
        this.status = "RUN";
        if (t == null)
            t = new Thread(this);
        t.start();
    }

    public void run() {
        int i = 0;
        while (i < 8) {
            i = i + 1;
            try {
                System.out.println("GO  " + i);
                Thread.sleep(300);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        this.status = "FINISH";
        System.out.println("inside " + this.status);
    }

    String getStatus() {
        return this.status;
    }
}

class DemoTest {

    @Test
    void test() {

        DemoRunnable demo = new DemoRunnable();
        demo.start();

        while (demo.getStatus() != "FINISH") {

        }
    }
}

Of course it's only the draft - I cut it short to make it more clear, but kept the same concept. At first I tried to test it without the while loop but junit test would finish before the Thread and only one GO would be printed out. After adding the loop everything looks fine GO is printed out correctly and then the status is changed but the test goes on forever :< Like if it was not noticing the status change.

  • when I remove sleeping then test does notice the change in status and while loop is broken
oscine
  • 15
  • 4
  • Also see my answer to this question: https://stackoverflow.com/questions/58041588/simulating-field-visibility-problem-in-java/58041789#58041789 – Johannes Kuhn Apr 12 '20 at 21:42
  • @JohannesKuhn for now I'm using system.out only in one Thread + this is not the matter of wrong comparison (in real code I'm comparing enums just written dirty example with string to make it more readable) – oscine Apr 12 '20 at 21:51
  • Declare the variable status `volatile`. That's the right thing to do. – Johannes Kuhn Apr 12 '20 at 21:51
  • How did you manage to call private class `DemoRunnable` from outside DemoTest class? After I put this private class inside `DemoTest`, the test succeeded. – Nowhere Man Apr 12 '20 at 22:18

0 Answers0