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