سؤال

When running a thread in Android/Java:

public void run()
{
   while (running)
   {
      if (moreTasksToExec())
      {
         task = getNextTask()
         task.exec();
      }
   }
}

Is it OK to let it run and not using a semaphore to block while no work needs to be executed?

I am only using one thread, so I need no inter-thread synchronization.

هل كانت مفيدة؟

المحلول

Two threads could get the same next task and try to run the same task at the same time. So I would think so.

نصائح أخرى

You might be better off with:

public void run()
{
  while (true) {
    task = getNextTask();  // blocks until task available
    if (task == null)
      break;
  }
}

getNextTask() returns null if it's time to stop running. Alternatively, check for "task == STOP_TASK" and have whatever code currently sets running=false post STOP_TASK onto the task queue.

Another approach is to use Thread.interrupt() to wake up a sleeper, but that always feels sleazy somehow. :-)

If you do retain the above approach, make sure "running" is declared volatile if it can be modified by another thread.

You should at least put a sleep in there so you don't hog the cpu.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top