Search code examples
androidmultithreadingwakelock

wakelock inside a running thread Android


I have this simple question:

In a service i need to run 2 more threads independent from each other, and i need a wakelock to let them be executed. I give you an example:

   wl.aquire();

    if (true) {
        mExecutorService.execute(thread1);
    }

    if (true) {
        mExecutorService.execute(thread2);
    }
   wl.release();

So, in this case, the wake lock will be released once the 2 threads have started or does it wait for them to finish?

If not, i need the wakelock to stay up while they're running, and release it only when the last thread has finished. How can i do that? Do i have to acquire new wakelocks inside the thread's body?

Thank you


Solution

  • According to the Executor execute() documentation: "Executes the given command at some time in the future. The command may execute in a new thread, in a pooled thread, or in the calling thread, at the discretion of the Executor implementation."

    So it depends on which concrete Executor you are using.

    I think you are supposed to use submit() to give a new job to an Executor.

    If you stick with the Executor, calling get() on the Future returned by submit() will block until the result is available.

    So you could call:

    Future<Result> result_1 = mExecutorService.execute(Runnable1);
    Future<Result> result_2 = mExecutorService.execute(Runnable2);
    
    result_1.get();
    result_2.get();
    

    Alternatively, you could start two threads and wait for them to finish:

    Thread t1 = new Thread(Runnable1);
    Thread t2 = new Thread(Runnable2);
    t1.start();
    t2.start();
    
    t1.join();
    t2.join();
    

    Hope this helps.