Question

Alongside the implicit User Interface thread, i have made two threads (runnables), both having a while loop inside them in which i periodically check for updates inside a message queue which I've implemented.

The problem at first was that the two while loops were infinite, and they changed so quickly and so much that they used up almost all the CPU of the device. So i thought about making the while loops sleep for about 100 milisec after each cycle, to let the other threads do their work, but i came across another issue:

NOW, the problem is that the threads sleep for 100 milliseconds, but they don't let the UI thread work during that time :( And what this does is make the UI laggy. When i drag something on the screen it lags a bit.

So what i want to do is make these threads (these while loops) check the message queue flag every 100 miliseconds, but during those 100 miliseconds i want to let the UI thread run. How can this be accomplished?

EDIT 1

I found the yield method, which stops the running of the current thread, but when do i call this? I would need to call the sleep thread and at the same time make it yield somehow ... ??

EDIT 2

The two classes are singletons, and i start them from the first Activity of the application, so when the app starts (the UI thread)

//Obtain object of singleton classes
ControllerSingleton controller = ControllerSingleton.getControllerSingleton();
OpponentSingleton opponent = OpponentSingleton.getOpponentSingleton();

//Start threads
/*--------CONTROLLER----------*/
Thread t;
t = new Thread( controller );       
t.setName("ControllerThread");
Log.i("Remy","Starting Controller thread...");
t.start();

/*--------OPPONENTS----------*/
t = new Thread( opponent );     
t.setName("OpponentThread");
Log.i("Remy","Starting Opponent thread...");
t.start();

And inside each run() i have the next code:

public void run() 
{
   while( true )
   {
      //Check if any messages in the queue
      if ( queueEmpty() == false )
      {
          //Do something ...              
      }
      /*HERE IS WHERE I WOULD LIKE TO TELL THE THREAD TO STOP AND WAIT FOR 100 ms*/
   }
}
Was it helpful?

Solution

I think that the thing you need to use is Handler. You might want to see this tutorial for example.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top