0
votes

How can I test Thread? A have got MyClass and I would like to test it. I know what is in List<Integer> numbers and I would like to test if in onThreadFinished(String someString) is right string value when Thread is finished. So how to create test for method onThreadFinished(String someString) after Thread is finished.

class MyClass {

  public void startMyClass(List numbers) {
      Thread thread = new Thread() {

        @Override
        public void run() {

          while(...) {
            // ...do something...
          }

          onThreadFinished(someString);
        }
      }
      thread.start();
  }


  protected void onThreadFinished(String someString) {
  }

}
2
If you're using threads raw like this then Thread.join() is used to wait for a thread to complete. A better solution is to use one of the classes from java.util.concurrent.markspace
Why would you wait for thread to finish to test string value. If you already know its value, you can simply use assertion to test it. "something" string seems to be a local variable here which will not be accessible after Thread execution completes.Developer

2 Answers

1
votes

Case 1: Do stuff, then wait for results, then continue.

myThread.join() is for cases when the code that created the thread does some more stuff after starting the thread, and then wants to wait for the thread's result. Once the thread's code is done, the thread dies, and thus the application continues execution after the join() call.

To give the application information from the thread, you'd have to store it somewhere, e.g. in a field dedicated for this. You don't have to worry about synchronization, because once the thread has died, all its actions will become "common knowledge", they are not privately timed (or whatever) any more.

Case 2: Keep doing stuff, and regularly check if results are available.

If instead your intention is to have some kind of game loop, where you keep doing stuff, and your extra thread is only meant to deliver some goods to you eventually (e.g. render a star background image while your game is already running), again you should hand it to the application in a field (aka class variable).

In that case, though, you have to worry about synchronization. Because as the game loop keeps checking if the field has changed from null to a value, the two threads are racing each other.

So, in that case you'd need an extra object to synchronize on, ideally a dedicated one for this task, e.g. final private Object lockForBackgroundCalculation = new Object();, and when the thread writes its result value into the other field, you wrap that statement into synchronized(lockForBackgroundCalculation){...}, and you also wrap your game loop's checking of the field value into the very same sync block text.

1
votes
Thread.join()

join() Waits for this thread to die.