开发者

Do I need a semaphore for my thread in Android/Java?

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 开发者_JAVA技巧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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜