Thread pool basically manages the pool of worker thread or it manages the collection of runnable and worker threads execute Runnable from queue.
Here is an example of creating threads 20 times and calling its runnable methods like this :
public class WorkerThread implements Runnable{
int n;
WorkerThread(int i){
n = i ;
}
@Override
public void run() {
Log.e(" Thread running " , Thread.currentThread().getName().toString()+ " = " + n );
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
Log.e(" Thread ending " , Thread.currentThread().getName().toString()+ " = " + n );
}
}
and from main class :
for (int i = 1; i<20 ; i++){
WorkerThread workerThread = new WorkerThread(i);
workerThread.run();
}
now output will be :
Thread running main = 1
Thread ending main = 1
Thread running main = 2
Thread ending main = 2
Thread running main = 3
Thread ending main = 3
Thread running main = 4
Thread ending main = 4
Thread running main = 5
Thread ending main = 5 and so on.....
But on the other hand Executor service is an interface that uses its method execute to executes threads here we use newFixedThreadPool method of class executors. A new fixedThreadPool method creates thread pool of number of given threads means if we are using Executors.newFixedThreadPool(5) then at a time only 5 threads will execute simultaneously and if more than 5 threads want to execute then they would held in queue until threads become available to execute.
if we are using Executor service with fixed thread pool then :
ExecutorService service = Executors.newFixedThreadPool(5);
for (int i = 1; i<20 ; i++){
Runnable r = new WorkerThread(i);
service.execute(r);
}
service.shutdown();
Output will be now :
Thread running pool-1-thread-5 = 5
Thread running pool-1-thread-3 = 3
Thread running pool-1-thread-2 = 2
Thread running pool-1-thread-1 = 1
Thread running pool-1-thread-4 = 4
Thread ending pool-1-thread-5 = 5
Thread running pool-1-thread-5 = 6
Thread ending pool-1-thread-3 = 3
Thread ending pool-1-thread-2 = 2
Thread ending pool-1-thread-1 = 1
Thread running pool-1-thread-2 = 8
Thread running pool-1-thread-1 = 9
Thread running pool-1-thread-3 = 7
etc.....
0 Comment(s)