简体   繁体   中英

when do we consider a worker thread as free in Executor Service

I am having a conceptual problem in understanding the working of fixedthreadpool of executor service.
Suppose I have a fixed pool thread of n threads and I am submitting several tasks to this service. Now if a worker is available, it executes the submitted task and other submitted tasks wait in the queue until a worker is free.
My question is, when do we consider a worker as a free worker thread ?
Do we consider a worker thread free as soon as it starts submitted task irrespective of task's completion or we consider a worker thread busy as long as submitted task is in progress.
Let's say we have a worker thread W1 in the pool and a Task Op1 is submitted to the executor.
W1 starts Op1 at time T1 and after some time Op1 finished its execution at time T3. Here T3 > T1
Now do we consider W1 as free as soon as it starts Op1 at time T1 or it is considered busy and will be free at time T3.

Thanks in advance !!

Well, it's very simple... let's get started.

  1. Thread Pool executes tasks. Tasks that are submitted to it are stored in the queue.
  2. A task implements the runnable interface, thus it has a run method that does not take any arguments and return void. This method acts as an entry point or the method that is called by the "thread that would be executing you task" in the thread pool.
  3. Now, back to the thread pool: a. Thread pool compromises of a internal queue could be ArrayBlockingQueue / LinkedBlockingQueue , etc... The main point is: it is always a queue. b.A group of threads that continuously poll this queue.

The thread that executes your task looks like this some what

void run() { while (true) { //Get the task from the thread pool internal queue (1) //Call the run method of the task. //If the execution of the task throws a Runtime exception - catch it and display it. (2) } }

So, as u can see, the worker will only be free if there are no task in the queue. The worker would either be polling the queue for task (1) or executing the task (2).

A worker thread is free when it is takes ing off the queue. Any given worker thread take's off the queue when it no longer is running the task. So it would look something like

private final BlockingQueue<Runnable> workQueue;

class WorkerThread {
   public void run(){
      while(true){
        Runnable r = workQueue.take(); // worker thread is 'free'
        r.run(); // worker thread is busy
      }
   }
}

So to answer your question, a particular worker thread is free when it is not executing a task submitted to the service.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM