abcdabcdefef abcdabcdefef - 2 months ago 7
Java Question

Issues with Threads. Trying to test a timer that utilizes threads and seem to get stuck in a loop

My TEST creates an instance of SimpleTimer with 1000 as a milliseconds measure to delay the thread by 1 second.

@Test
public void testSimpleTimerAsThread() throws InterruptedException
{
SimpleTimer st = new SimpleTimer(1000);
st.start();
Thread.sleep(250);
for(int x = 0; x<5; x++)
{
assertEquals(x, st.getRound());
Thread.sleep(1000);
}
}


My METHOD

timeChanged() just updates the round number and calls for all observers to update their time.

public void start()
{
for(int r = 0; r<5; r++)
{
try
{
timeChanged();
Thread.sleep(1000);
}
catch (InterruptedException e)
{
}
}
}


SimpleTimer extends Thread and implements an interface that doesn't really mess with this code.

When I run this i get the java assertion error saying it expected 0 but was 5 so x never incremented and the round increased by 5.

Answer

Your SimpleTimer works in the same thread as the rest, so when you call st.start() what happens is it goes straight there and executes everything, then the rest of your test is executed. You need to put all of your SimpleTimer logic in run method instead of start method and remove start method completely, Thread class already has it implemented in the right way (but keep call to st.start(), it's ok, that's how you start a new Thread). But even then it's not gonna work as expected, but this will actually be concurrency problem, not a mistake. I mean there is a slight possibility that it's gonna work (only sometimes, not always), because of the delays, but relying on delays it's not really a good idea.

Comments