开发者

Thread and battery

开发者 https://www.devze.com 2023-03-22 03:21 出处:网络
I have 1 problem and 2 options for the implementation and I would like to know which one is the best in an Android environment (basicly best practice and which one is using less battery).

I have 1 problem and 2 options for the implementation and I would like to know which one is the best in an Android environment (basicly best practice and which one is using less battery).

My problem: I have 4 Runnable implementations, which Runnable has a lis开发者_如何学运维t of tasks that need to be executed in separate threads. Those Runnable will have no task for a long period of time and then a lot of tasks to execute (each Runnable executes their tasks an in sequential order), then nothing for a long time and and so on...

1st implementation

My fist implementation was to create 4 Thread. Each threads is in charged of 1 Runnable. Each thread runs all the tasks, when the list is empty the Runnable Pause the thread (with wait()), when another tasks is added to the list the thread is waken up (with notify()). Here is the code of the run method for the Runnable:

  public void run() {
    while (!terminated) {
      while ( taskList.size()> 0 ) {
        Task task = taskList.get(0);
        taskList.remove(task);
        handleTask(task);
      }

      synchronized(taskList) {
         if (taskList.size()==0)
           taskList.wait();
      }
    }
  }

First question: is a thread in a pause state using much ressource?

2nd implementation

In my second implementation I thinking of using Executors.newCachedThreadPool() (as in the AsyncTask implementation). Basicly I will ask a thread to the pool when my Runnable have tasks to run and the system is in charge to provide me with an available thread and destroy it after a certain period of inactivity. Because my 4 Runnable will have long period without tasks (execpt maybe 1 Runnable) I pretty sure the behaviour of my pool will be something like:

  • always 1 thread busy
  • create 1 thread, delete 1 thread,
  • create 2 threads, delete 2 treads,
  • create 1 thread ...

Threads will probably never get reused (except if I set a really long period of inactivity).

So what is the best option? Having only 4 threads which spend most of their time in a pause state or create / destroy a lot of threads but having them only when I need them.

Thanks for your help,

JimBoy.


Keep your threads in a paused state. That way, they don't take up any resources. Don't ever keep a thread busy unless there's work to be done.

However, looking at what you appear to be doing there, it sounds like you may want to look into a subclass of a BlockingQueue.

0

精彩评论

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