简体   繁体   中英

why is thread.join commonly used to stop threads in android

looking at several android examples i see a trend where threads are paused using join() method:

EDIT: please assume that the 2 threads are properly defined. edited the calls to join()

public class MainUI extends Activity{
   private GraphicsViewThread g;
   private BackendDataViewThread b;

   void onCreate(){
      g = new GraphicsViewThread();
      g.start();
      b = new BackendDataViewThread();
      b.start();
   }
   .
   .
   .
   void pauseGame(){
      try {
        g.join();
      }catch (InterruptedException e){
         e.printStackTrace();
      }
      try {
        b.join();
      }catch (InterruptedException e){
         e.printStackTrace();
      }
      GraphicsViewThread = null;
      BackendDataViewThread  = null;
   }
}
  1. which thread does GraphicsViewThread and BackendDataViewThread join to?
  2. what is the need for using join()? can i not set the references immediately to null?

I suspect your code doesn't compile, but regardless - I'll answer.
This is not just about Android, but plain Java.
Using "join" ensures that you code will wait for the thread to end.
Isn't this exactly what you want?
In addition, don't set references of thread to null.
You cannot guarantee exactly when a thread ends, so it will be bad practice to set the thread object to null, prior to its ending.

It's a rendezvous function, which means that the thread you are referencing (GraphicsViewThread for example) will join the parent/main/UI thread at that point (which ever gets there first). That's the thread that is actually drawing the UI. You can't just set the reference to null, because it's just a reference. The task will still be working in the background.

As far as I've worked with Android, and analyzed it, I've learned just to avoid Threads. Use, AsyncTask or some other similar container. It's much more managable.

Edit: I've just noticed, as the others mentioned, your code is not correct, it probably will not work.

You have several things wrong in the code and are confused about the purpose of Thread.join . The join method has to be called on an instance of a Thread . So you'll want to call join on g and b . Before you call join, you normally would have to notify those threads in some way that you'd like them to stop. As zaske mentions, join will wait until that thread is done before continuing execution in the thread invoking pauseGame .

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