简体   繁体   中英

how to test result when thread is finished - java

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) {
  }

}
Thread.join()

join()等待该线程死亡。

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, eg 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 (eg 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, eg 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM