0

I'm making a basic android game, I have a fragment that displays the game world. When I open that fragment I create a new thread that just waits until my NetworkThread gets the world from the server. Also my GetWorldThread is a static Thread that I only initialize inside the fragment.

This is how my GetWorldThread looks like:

synchronized (this)
{
    try 
    {
        Log.d("getWorldThread", "waiting()");
        wait();
    } 
    catch (InterruptedException e)
    {
        e.printStackTrace();
    }  
}

and my NetworkThread looks like this

if (buffer instanceof World)
{
    synchronized (WorldFragment.getWorldThread)
    {
        World.setWorld(((World) buffer));                
        Log.d("NetworkThread", "notifying World");

        WorldFragment.getWorldThread.notify();
    }

}

My code works, but I want to know if there is a way to do this more elegant?.

Ravindra babu
  • 37,698
  • 11
  • 250
  • 211
bhazero025
  • 337
  • 4
  • 15

1 Answers1

1

As mentioned in documentation you always should use wait() in while loop. So your code may not work correctly.

More elegant way is to use more high-level abstracnions. For example Future and standart FutureTask. This way allows you don't write low-level stuff like loops and therefore to avoid mistakes.

Update: Also note that there are Conditions/Locks intended for wait/synchronyzed substitution as described here. In fact, using wait() is obsolete in 2017

Community
  • 1
  • 1
ADS
  • 708
  • 3
  • 14